<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Backend;
use DateInterval;
use DateTime;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Log;

/**
 * 工单
 *
 * @icon fa fa-circle-o
 */
class Work extends Backend
{

    /**
     * Work模型对象
     * @var \app\admin\model\Work
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $relationWith = 'Product';
    protected $searchFields = ['order_code','res_mobile','res_receiver','product.name','admin_shipper_code','user_shipper_code','product.code','user.username','user.mobile','id','channel.name','status','admin.username','res_address','remarks'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Work;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("shipperList", $this->model->getShipper());
        $this->view->assign("isLiugcList", $this->model->isLiugc());
        $this->view->assign("ishuangouList", $this->model->ishuangou());
        $this->view->assign("reasonList", $this->model->getDamageReasonList());
        $this->view->assign("channelList", $this->model->getchannel());
        $this->view->assign("isStatuslList", $this->model->isStatus());
        $this->view->assign("isStatuslListtwo", $this->model->isStatustwo());
        $this->view->assign("problemList", $this->model->getproblemList());
        $this->view->assign("cidList", $this->model->cidList());
        $this->view->assign("workBaoList", $this->model->workBaoList());

        $tree = Tree::instance();
        $tree->init(collection(Db::name("repair")->where('type','in','1')->select())->toArray(), 'pid');
        $this->categorylist_zl = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata_zl = [];
        foreach ($this->categorylist_zl as $k => $v) {
            $categorydata_zl[$v['id']] = $v;
        }
        $this->view->assign("repair_zl", $categorydata_zl);

        $tree = Tree::instance();
        $tree->init(collection(Db::name("repair")->where('type','in','2,0')->select())->toArray(), 'pid');
        $this->categorylist_fzl = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata_fzl = [];
        foreach ($this->categorylist_fzl as $k => $v) {
            $categorydata_fzl[$v['id']] = $v;
        }
        $this->view->assign("repair_fzl", $categorydata_fzl);


        $tree = Tree::instance();
        $tree->init(collection(Db::name("problem")->where('type','in','1,0')->select())->toArray(), 'pid');
        $this->categorylist_zl = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata_zl = [];
        foreach ($this->categorylist_zl as $k => $v) {
            $categorydata_zl[$v['id']] = $v;
        }
        $this->view->assign("parentList_zl", $categorydata_zl);

        $tree = Tree::instance();
        $tree->init(collection(Db::name("problem")->where('type','in','2,0')->select())->toArray(), 'pid');
        $this->categorylist_fzl = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata_fzl = [];
        foreach ($this->categorylist_fzl as $k => $v) {
            $categorydata_fzl[$v['id']] = $v;
        }
        $this->view->assign("parentList_fzl", $categorydata_fzl);
    }

    // 批量改为类型一
    public function userbao($ids)
    {
        foreach ($ids as $k => $v) {
            $data = [
                'is_bao' => 1
            ];
            $this->model->where('id', $ids[$k])->update($data);
        }
        $this->success();
    }
    function secondsToTime($seconds) {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds - ($hours * 3600)) / 60);
        $seconds = $seconds - ($hours * 3600) - ($minutes * 60);
        return str_pad($hours, 2, '0', STR_PAD_LEFT).':'.str_pad($minutes, 2, '0', STR_PAD_LEFT).':'.str_pad($seconds, 2, '0', STR_PAD_LEFT);
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $redis = new \think\cache\driver\Redis(['length' => 3]);
        $is_gq = $_GET['is_gq']??0;
        if($is_gq == 1){
            $redis->set('is_gq', $is_gq);
        }
        if ($this->request->isAjax()) {
            $redis = new \think\cache\driver\Redis(['length' => 3]);

            $is_gq = $redis->get('is_gq');
            $is_gq = $is_gq??0;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $with = $this->relationSearch && $this->relationWith ? $this->relationWith : '';
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //var_dump(json_decode()$where);exit;
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
           // var_dump($filter);
            $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
            $factory_id = Db::name("admin")->where(['id'=>$this->auth->id])->value("factory_id");
            if($is_gq == 1){
                if($admin_type == 1){
                    // $where['ago_admin_id'] = $this->auth->id;
                    $list = $this->model
                        ->with(['Product','User','Channel','Admin','Factory'])
                        ->where($where)
                        ->where(['work.is_gq'=>1])
                        // ->where('ago_admin_id',$this->auth->id)
                        // ->where('(work.ago_admin_id = '.$this->auth->id.' or work.ago_admin_id IS null)')
                        ->field("product.producetime,product.warranty")

                        ->order($sort, $order)
                        ->paginate($limit);
                }elseif($admin_type == 2){
                    //$where['admin_id'] = $this->auth->id;
                    $list = $this->model
                        ->with(['Product','User','Channel','Admin','Factory'])
                        ->where($where)
                        ->where("work.status",'not in','11')
                        ->where(['work.is_gq'=>1])
                        ->field("product.producetime,product.warranty")
                        //->where('admin_id',$this->auth->id)
                        //->where('(work.admin_id = '.$this->auth->id.' or work.admin_id IS null)')
                        //->whereOr(['admin_id'=>null,'admin_id'=>$this->auth->id])
                        ->order($sort, $order)
                        ->paginate($limit);
                }elseif($admin_type == 3){
                    //$where['admin_id'] = $this->auth->id;
                    $list = $this->model
                        ->with(['Product','User','Channel','Admin','Factory'])
                        ->where($where)
                        ->where('work.factory_id',$factory_id)
                        ->where("work.status",'in','4,5,6,7,8,9,10')
                        ->where(['work.is_gq'=>1])
                        ->field("product.producetime,product.warranty")
                        //->whereOr(['admin_id'=>null,'admin_id'=>$this->auth->id])
                        ->order($sort, $order)
                        ->paginate($limit);
                }else{
                    $list = $this->model
                        ->with(['Product','User','Channel','Admin','Factory'])
                        ->where($where)
                        ->where(['work.is_gq'=>1])
                        ->field("product.producetime,product.warranty")
                        ->order($sort, $order)
                        ->paginate($limit);
                }
            }else{
                if($admin_type == 1){
                    // $where['ago_admin_id'] = $this->auth->id;
                    $list = $this->model
                        ->with(['Product','User','Channel','Admin','Factory'])
                        ->where($where)
                        // ->where('ago_admin_id',$this->auth->id)
                        // ->where('(work.ago_admin_id = '.$this->auth->id.' or work.ago_admin_id IS null)')
                        ->field("product.producetime,product.warranty")
                        ->order($sort, $order)
                        ->paginate($limit);
                }elseif($admin_type == 2){
                    //$where['admin_id'] = $this->auth->id;
                    $list = $this->model
                        ->with(['Product','User','Channel','Admin','Factory'])
                        ->where($where)
                        ->where("work.status",'not in','11')
                        ->field("product.producetime,product.warranty")
                        //->where('admin_id',$this->auth->id)
                        //->where('(work.admin_id = '.$this->auth->id.' or work.admin_id IS null)')
                        //->whereOr(['admin_id'=>null,'admin_id'=>$this->auth->id])
                        ->order($sort, $order)
                        ->paginate($limit);
                }elseif($admin_type == 3){
                    //$where['admin_id'] = $this->auth->id;
                    $list = $this->model
                        ->with(['Product','User','Channel','Admin','Factory'])
                        ->where($where)
                        ->where('work.factory_id',$factory_id)
                        ->where("work.status",'in','4,5,6,7,8,9,10')
                        ->field("product.producetime,product.warranty")
                        //->whereOr(['admin_id'=>null,'admin_id'=>$this->auth->id])
                        ->order($sort, $order)
                        ->paginate($limit);
                }else{
                    $list = $this->model
                        ->with(['Product','User','Channel','Admin','Factory'])
                        ->where($where)
                        ->field("product.producetime,product.warranty")
                        ->order($sort, $order)
                        ->paginate($limit);
                }
            }
//echo $this->model->getLastSql();
            //echo $this->model->getLastSql();
            $t = time();
            foreach ($list->items() as $k=>$v){
                //$product = Db::name("product")->where(['id'=>$v['product_id']])->where('deletetime',null)->find();
                //$where_r['id'] = $product['factory_id'];
                //$factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
                //echo Db::name("factory")->getLastSql();
                //$list->items()[$k]['factory_tile'] = $factory['title'];
               /*$is_two_wx =  Db::name("work")->where(['product_id'=>$v['product_id']])->where('id','lt',$v['id'])->find();
               if($is_two_wx){
                   $list->items()[$k]['is_two'] = 1;
               }else{
                   $list->items()[$k]['is_two'] = 0;
               }*/
                if($v['status'] == 10){
                    //工厂总时间
                    $gc_z_time = $v['factorysend_time']-$v['confirm_time'];

                    //非工厂处理时间
                    if($v['voucher_aud_time']){
                        $f_gc_z_time = $v['voucher_aud_time']-$v['detection_time'];
                    }else{
                        $f_gc_z_time = 0;
                    }

                    //工厂处理时间

                    $gc_cl_time = $gc_z_time - $f_gc_z_time;
                    //echo $gc_z_time."_".$f_gc_z_time."_".$gc_cl_time;exit;
                    $list->items()[$k]['gc_cl_time'] = self::timeToString($gc_cl_time);
                }else{
                    $list->items()[$k]['gc_cl_time'] = "";
                }


                $pro_time = strtotime($v['producetime'])+$v['warranty']*86400;
                if($pro_time > $t){
                    $list->items()[$k]['pro_bao'] = "1";//在保
                    /*if(isset($filter['pro_bao']) && $filter['pro_bao'] == 0){
                        unset($list[$k]);
                    }*/
                }else{
                    $list->items()[$k]['pro_bao'] = "0";//过保
                    /*if(isset($filter['pro_bao']) && $filter['pro_bao'] == 1){
                        unset($list[$k]);
                    }*/
                }
                $bl_str ='';
                $problemlist = Db::name("problem")->where('id','in',$v['problem'])->select();
                foreach ($problemlist as $kk=>$vv){
                    $bl_str .= $vv['name'].",";
                }
                $bl_str = trim($bl_str,',');
                $list->items()[$k]['bl_str'] = $bl_str;
                $list->items()[$k]['user_content'] =str_replace('<br>','', str_replace('</br>','',  str_replace('</p>','', str_replace("<p>", "", $v['user_content']))));
                if($v['is_bao'] == 0){
                    $work_time = strtotime($v['real_pay_time'])+365*86400;
                    if($work_time > $t){
                        $list->items()[$k]['work_bao'] = "1";//在保
                        //$list->items()[$k]['work_bao'] = 1;
                        /*if(isset($filter['work_bao']) && $filter['work_bao'] == 0){
                            unset($list[$k]);
                        }*/
                    }else{
                        $list->items()[$k]['work_bao'] = "0";//过保
                        //$list->items()[$k]['work_bao'] = 0;
                        /*if(isset($filter['work_bao']) && $filter['work_bao'] == 1){
                            unset($list[$k]);
                        }*/
                    }
                }else{
                    $list->items()[$k]['work_bao'] = "1";//在保
                    //$list->items()[$k]['work_bao'] = 1;
                    /*if(isset($filter['work_bao']) && $filter['work_bao'] == 0){
                        unset($list[$k]);
                    }*/
                }

                $user_shipper_name = Db::name("shipper")->where(['id'=>$v['user_shipper_id']])->value("name");
                $admin_shipper_name = Db::name("shipper")->where(['id'=>$v['admin_shipper_id']])->value("name");
                /*if($v['admin_shipper_id'] == 10000){
                    $admin_shipper_name = '不用寄出';
                }else{
                    $admin_shipper_name = Db::name("shipper")->where(['id'=>$v['admin_shipper_id']])->value("name");
                }*/

                $list->items()[$k]['user_shipper_name'] = $user_shipper_name;
                $list->items()[$k]['user_shipper_code'] = $user_shipper_name.'-'.$v['user_shipper_code'];
                $list->items()[$k]['admin_shipper_code'] = $admin_shipper_name.'-'.$v['admin_shipper_code'];
               // $list->items()[$k]['admin_shipper_name'] = $admin_shipper_name;
                $list->items()[$k]['admin_type'] = $admin_type;
                if($v['fan_time']){
                    $list->items()[$k]['fan_time'] = self::timeToString($v['fan_time']);
                }else{
                    $list->items()[$k]['fan_time'] = "";
                }
                $bl_str_status = '';
                if($v['factory_status']){
                    $repairlist = Db::name("repair")->where('id','in',$v['factory_status'])->select();
                    foreach ($repairlist as $kk=>$vv){
                        $bl_str_status .= $vv['name'].",";
                    }
                    $bl_str_status = trim($bl_str_status,',');
                }
                $list->items()[$k]['factory_status'] = $bl_str_status;
                $bl_str_problem = '';
                if($v['problem']){
                    $repairlist = Db::name("problem")->where('id','in',$v['problem'])->select();
                    foreach ($repairlist as $kk=>$vv){
                        $bl_str_problem .= $vv['name'].",";
                    }
                    $bl_str_problem = trim($bl_str_problem,',');
                }
                $list->items()[$k]['problem'] = $bl_str_problem;

            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            $redis->set('is_gq', 0);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看
     */
    public function delindex()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $with = $this->relationSearch && $this->relationWith ? $this->relationWith : '';
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //var_dump(json_decode()$where);exit;
            $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
            $factory_id = Db::name("admin")->where(['id'=>$this->auth->id])->value("factory_id");
            if($admin_type == 1){
                // $where['ago_admin_id'] = $this->auth->id;
                $list = $this->model->onlyTrashed()
                    ->with(['Product','User','Channel','Admin','Factory'])
                    ->where($where)
                    // ->where('ago_admin_id',$this->auth->id)
                    //->where('(work.ago_admin_id = '.$this->auth->id.' or work.ago_admin_id IS null)')
                    ->field("product.producetime,product.warranty")
                    ->order($sort, $order)
                    ->paginate($limit);
            }elseif($admin_type == 2){
                //$where['admin_id'] = $this->auth->id;
                $list = $this->model->onlyTrashed()
                    ->with(['Product','User','Channel','Admin','Factory'])
                    ->where($where)
                    ->where("work.status",'not in','11')
                    ->field("product.producetime,product.warranty")
                    //->where('admin_id',$this->auth->id)
                    //->where('(work.admin_id = '.$this->auth->id.' or work.admin_id IS null)')
                    //->whereOr(['admin_id'=>null,'admin_id'=>$this->auth->id])
                    ->order($sort, $order)
                    ->paginate($limit);
            }elseif($admin_type == 3){
                //$where['admin_id'] = $this->auth->id;
                $list = $this->model->onlyTrashed()
                    ->with(['Product','User','Channel','Admin','Factory'])
                    ->where($where)
                    ->where('work.factory_id',$factory_id)
                    ->where("work.status",'in','4,5,6,7,8,9,10')
                    ->field("product.producetime,product.warranty")
                    //->whereOr(['admin_id'=>null,'admin_id'=>$this->auth->id])
                    ->order($sort, $order)
                    ->paginate($limit);
            }else{
                $list = $this->model->onlyTrashed()
                    ->with(['Product','User','Channel','Admin','Factory'])
                    ->where($where)
                    ->field("product.producetime,product.warranty")
                    ->order($sort, $order)
                    ->paginate($limit);
            }
            //echo $this->model->getLastSql();
            $t = time();
            foreach ($list->items() as $k=>$v){
                if($v['status'] == 10){
                    //工厂总时间
                    $gc_z_time = $v['factorysend_time']-$v['confirm_time'];

                    //非工厂处理时间
                    if($v['voucher_aud_time']){
                        $f_gc_z_time = $v['voucher_aud_time']-$v['detection_time'];
                    }else{
                        $f_gc_z_time = 0;
                    }

                    //工厂处理时间

                    $gc_cl_time = $gc_z_time - $f_gc_z_time;
                    //echo $gc_z_time."_".$f_gc_z_time."_".$gc_cl_time;exit;
                    $list->items()[$k]['gc_cl_time'] = self::secondsToTime($gc_cl_time);
                }else{
                    $list->items()[$k]['gc_cl_time'] = "";
                }


                $pro_time = strtotime($v['producetime'])+$v['warranty']*86400;
                if($pro_time > $t){
                    $list->items()[$k]['pro_bao'] = "在保";
                }else{
                    $list->items()[$k]['pro_bao'] = "过保";
                }
                if($v['is_bao'] == 0){
                    //$product = Db::name("product")->where(['id'=>$v['product_id']])->where('deletetime',null)->find();
                    $work_time = strtotime($v['real_pay_time'])+365*86400;
                    if($work_time > $t){
                        $list->items()[$k]['work_bao'] = "在保";
                        //$list->items()[$k]['work_bao'] = 1;
                    }else{
                        $list->items()[$k]['work_bao'] = "过保";
                        //$list->items()[$k]['work_bao'] = 0;
                    }
                }else{
                    $list->items()[$k]['work_bao'] = "在保";
                    //$list->items()[$k]['work_bao'] = 1;
                }

                $user_shipper_name = Db::name("shipper")->where(['id'=>$v['user_shipper_id']])->value("name");
                /*if($v['admin_shipper_id'] == 10000){
                    $admin_shipper_name = '不用寄出';
                }else{
                    $admin_shipper_name = Db::name("shipper")->where(['id'=>$v['admin_shipper_id']])->value("name");
                }*/

                $list->items()[$k]['user_shipper_name'] = $user_shipper_name;
                // $list->items()[$k]['admin_shipper_name'] = $admin_shipper_name;
                $list->items()[$k]['admin_type'] = $admin_type;
                if($v['fan_time']){
                    $list->items()[$k]['fan_time'] = self::timeToString($v['fan_time']);
                }else{
                    $list->items()[$k]['fan_time'] = "";
                }

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * @param int $second
     * @return string
     * @author: liugong
     * @Time: 2022/11/17 14:49
     * 时间戳抓换成字符串
     */
    public  function timeToString(int $second):string
    {
        $day = floor($second/(3600*24));
        $second = $second%(3600*24);//除去整天之后剩余的时间
        $hour = floor($second/3600);
        $second = $second%3600;//除去整小时之后剩余的时间
        $minute = floor($second/60);
        $second = $second%60;//除去整分钟之后剩余的时间
        //返回字符串
        // str = $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒';
        if($day >0 && $hour >0){
            return $day.'天'.$hour.'小时' ;
        }
        if($day == 0 && $hour >0){
            return $hour.'小时' ;
        }
        if($day ==0 && $hour ==0 && $minute >0){
            return $minute.'分' ;
        }
        return "";
    }
    public function getproduct(){
        $ids = $this->request->get("id");
        $product = Db::name("product")->where(['id'=>$ids])->find();
        $factory = Db::name("factory")->where(['id'=>$product['factory_id']])->find();
        $list['product_name'] = $product['name'];
        $list['factory_title'] = $factory['title'];
        $list['factory_name'] = $factory['name'];
        $list['factory_phone'] = $factory['phone'];
        $list['factory_address'] = $factory['address'];
        $result = array( "rows" => $list);

        return json($result);
    }

    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 审核
     */
    public function shenhe($ids=null){
        $row = $this->model->get($ids);
        $status = $this->request->post('status');
        $id = $this->request->post('id');
        if (empty($status)) {
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['producetime'] = $product['producetime'];
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    //$list['work_bao'] = "在保";
                    $list['work_bao'] = 1;
                }else{
                    //$list['work_bao'] = "过保";
                    $list['work_bao'] = 0;
                }
            }else{
                //$list['work_bao'] = "在保";
                $list['work_bao'] = 1;
            }
            $list['factory_tile'] = $factory['title'];

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];

            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

           /* if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";

                }else{
                    $list['work_bao'] = "过保";

                }
            }else{
                $list['work_bao'] = "在保";

            }*/
            if($list['product_name'] == '数据线'){
                $this->view->assign("is_sjx", 1);
            }else{
                $this->view->assign("is_sjx", 0);
            }
            $this->view->assign( 'row', $list);
            $this->view->assign("work_bao", $list['work_bao']);
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
       // $status = $params['status'];
        //$status = 2;
        if(!$status){
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }

        $updata['status'] = $status;
        Db::name("work")->where(['id'=>$id])->update($updata);
        $this->success("操作成功");
    }
    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 审核查看
     */
    public function shenhelook($ids=null){
        $row = $this->model->get($ids);
        $status = $this->request->post('status');
        $id = $this->request->post('id');
        if (empty($status)) {
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,p.producetime")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];

            $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
            $list['user_shipper_code'] = $user_shipper_name."-".$list['user_shipper_code'];
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";

                }else{
                    $list['work_bao'] = "过保";

                }
            }else{
                $list['work_bao'] = "在保";

            }

            $this->view->assign( 'row', $list);
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        // $status = $params['status'];
        //$status = 2;
        if(!$status){
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }

        $updata['status'] = $status;
        Db::name("work")->where(['id'=>$id])->update($updata);
        $this->success("操作成功");
    }
    public function shenhechehui($ids=null){
        $row = $this->model->get($ids);
        $chehui = $this->request->post('chehui');
        $id = $this->request->post('id');
        if (empty($chehui)) {
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $this->view->assign( 'row', $list);
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }


        $updata['status'] = $chehui;
        Db::name("work")->where(['id'=>$id])->update($updata);
        $this->success("操作成功");
    }
    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 审核通过
     */
    public function shenhere($ids=null){
        $status = $this->request->post('status');
        $reject = $this->request->post('reject');
        $id = $this->request->post('id');
        $work_bao = $this->request->post('work_bao');
        $image = $this->request->post('image');
        $order_image = $this->request->post('order_image');

       // var_dump($reject);
        //echo $id."_".$ids;
        if(!$status){
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        if($work_bao == 1){
            $work_time = strtotime($work_data['real_pay_time'])+365*86400;
            if($work_time > time()){

                $work_bao = 0;
            }else{
                $work_bao = 1;
            }
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        //echo $status."_".$id;
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['status'] = $status;
        $product_name = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if($product_name['name'] == "数据线"){
            $updata['status'] = 9;
        }
        if($status == 2){
            $params = $this->request->post('row/a');
            $status_name = "驳回";
           // $updata['reject'] = $reject;
            $title = '工单状态变更通知';
            $content = "您提交的工单".$product_data['name']."已被驳回!";
            $admincontent = "工单".$product_data['name']."已被驳回!";
            $log_content = $admin_data['nickname']."驳回工单，驳回原因：".$reject;
        }elseif ($status == 3){
            $status_name = "审核通过";
            $title = '工单状态变更通知';
            $content = "您提交的工单“".$product_data['name']."“已经审核通过!客服正在处理中。";
            $admincontent = "工单“".$product_data['name']."“已经审核通过!";
            $log_content = $admin_data['nickname']."审核通过，待用户寄出";
        }

        $openid_data = Db::name("openid")->where(['uid'=>$work_data['user_id']])->find();
        if($openid_data){
            $config = get_addon_config('third');

            $appId = $config['wechat']['app_id'];
            $appSecret = $config['wechat']['app_secret'];
            /*$acc_url = "https://api.weixin.qq.com/cgi-bin/token";
            $acc_arr['grant_type'] = "client_credential";
            $acc_arr['appid'] = $appId;
            $acc_arr['secret'] = $appSecret;
            $acc_data = \app\common\model\User::sendCurl(stripslashes($acc_url), $acc_arr, 'get',
                array('User-Agent: Apifox/1.0.0 (https://apifox.com)'));
            $acc_data_arr = json_decode($acc_data,true);*/
            $redis = new \think\cache\driver\Redis(['length' => 3]);
            $token = $redis->get('wechat_access_token');
            if(!$token){
                $acc_url = "https://api.weixin.qq.com/cgi-bin/token";
                $acc_arr['grant_type'] = "client_credential";
                $acc_arr['appid'] = $appId;
                $acc_arr['secret'] = $appSecret;
                $acc_data = \app\common\model\User::sendCurl(stripslashes($acc_url), $acc_arr, 'get',
                    array('User-Agent: Apifox/1.0.0 (https://apifox.com)'));
                $acc_data_arr = json_decode($acc_data,true);
                $token = $acc_data_arr['access_token'];
                $redis->set('wechat_access_token', $token, 7000);
            }
           // var_dump($acc_data_arr);

            $auth_arr['template_id'] = "kJkr4_X8Lc8t1I5Roi1UBoq6X7UZReE56ld2edI-Crc";
            $auth_arr['page'] = "pages/order/detail?id=".$work_data['id'];
            $auth_arr['touser'] = $openid_data['openid'];
            $auth_data['character_string3']['value'] = $product_data['code'];
            $auth_data['thing6']['value'] = $product_data['name'];
            $auth_data['phrase4']['value'] = "待寄出";
            $auth_arr['data'] = $auth_data;
            $auth_arr['miniprogram_state'] = "formal";
            $auth_arr['lang'] = "zh_CN";
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$token;
            $appid_data = \app\common\model\User::sendCurl(stripslashes($url), json_encode($auth_arr,true), 'post',
                array('Content-Type:application/json'));
            Log::write("发送请求信息shenhere：".json_encode($auth_arr)."__appid_data:".json_encode($appid_data));
        }

        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $updata['auditing_admin_status'] = $admin_data['username']."-".$status_name;
        $updata['auditing_time'] = time();
        $updata['image'] = $image;
        $updata['order_image'] = $order_image;
        if($work_bao == 1){
            $updata['is_bao'] =$work_bao;
        }
        Db::name("work")->where(['id'=>$id])->update($updata);
         $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],$title,$content,$id);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],$admincontent,$content,$id);
        }

        //echo Db::name("work")->getLastSql();
        $this->success("操作成功");
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 审核驳回
     */
    public function shenheresu(){
        $reject = $this->request->post('reject');
        $id = $this->request->post('id');
        $status = 2;

        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['status'] = $status;
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        if($status == 2){
           // $params = $this->request->post('row/a');
            $status_name = "驳回";
            $updata['reject'] = $reject;
            $title = '工单状态变更通知';
            $content = "您提交的工单".$product_data['name']."已被驳回!";
            $admincontent = "工单".$product_data['name']."已被驳回!";
            $log_content = $admin_data['nickname']."驳回工单，驳回原因：".$reject;
        }elseif ($status == 3){
            $status_name = "审核通过";
            $title = '审核通过';
            $content = '审核通过';
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $updata['auditing_admin_status'] = $admin_data['username']."-".$status_name;
        $updata['auditing_time'] = time();
        $updata['reject_time'] = time();
        $updata['reject_admin'] = $admin_data['nickname'];
        Db::name("work")->where(['id'=>$id])->update($updata);
         $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],$title,$content,$id);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],$title,$admincontent,$id);
        }
        $openid_data = Db::name("openid")->where(['uid'=>$work_data['user_id']])->find();
        if($openid_data && $status == 2){
            $config = get_addon_config('third');

            $appId = $config['wechat']['app_id'];
            $appSecret = $config['wechat']['app_secret'];
            $redis = new \think\cache\driver\Redis(['length' => 3]);
            $token = $redis->get('wechat_access_token');
            if(!$token){
                $acc_url = "https://api.weixin.qq.com/cgi-bin/token";
                $acc_arr['grant_type'] = "client_credential";
                $acc_arr['appid'] = $appId;
                $acc_arr['secret'] = $appSecret;
                $acc_data = \app\common\model\User::sendCurl(stripslashes($acc_url), $acc_arr, 'get',
                    array('User-Agent: Apifox/1.0.0 (https://apifox.com)'));
                $acc_data_arr = json_decode($acc_data,true);
                $token = $acc_data_arr['access_token'];
                $redis->set('wechat_access_token', $token, 7000);
            }



            $auth_arr['template_id'] = "sOpB_Xk_zKFLlX-fgXjyVwaAHxkcE_paCTaLCjs0WWs";
            $auth_arr['page'] = "pages/order/detail?id=".$work_data['id'];
            $auth_arr['touser'] = $openid_data['openid'];
            $auth_data['phrase2']['value'] = "已驳回";
            $auth_data['thing3']['value'] = mb_substr($reject, 0, 20);
            $auth_data['time10']['value'] = date('Y-m-d',time());

            $auth_arr['data'] = $auth_data;
            $auth_arr['miniprogram_state'] = "formal";
            $auth_arr['lang'] = "zh_CN";
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$token;
            $appid_data = \app\common\model\User::sendCurl(stripslashes($url), json_encode($auth_arr,true), 'post',
                array('Content-Type:application/json'));
            Log::write("发送请求信息shenheresu：".json_encode($auth_arr)."__appid_data:".json_encode($appid_data));
        }
        //echo Db::name("work")->getLastSql();exit;
        $this->success("操作成功");
    }

    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 一驳回查看详情
     */
    public function bohuide($ids=null){
        $list = Db::name("work")->alias('w')
            ->field("w.*,p.code as product_code,p.name as product_name")
            ->join("product p",'w.product_id = p.id', 'LEFT')
            ->where(['w.id'=>$ids])
            ->find();
        //$result = array("row" => $list);
        $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
        $where_r['id'] = $product['factory_id'];
        $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
        //echo Db::name("factory")->getLastSql();
        $list['factory_tile'] = $factory['title'];

        $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
        $list['admin_username'] = $admin['username'];
        $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
        $list['channel_name'] = $channel['name'];
        $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
        $list['user_shipper_code'] = $user_shipper_name.$list['user_shipper_code'];
        $list['reject_time'] = date('Y-m-d H:i:s',$list['reject_time']);
        $this->view->assign( 'row', $list);
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }
    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 手动上传用户快递单号
     */
    public function usersend($ids = null){
        //if ($this->request->isAjax()) {
        $row = $this->model->get($ids);
        if (!$row) {

            //return json($result);
            return $this->view->fetch();
            $this->error(__('No Results were found'));
        }


        $params = $this->request->post('row/a');
        if (empty($params)) {
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,p.factory_id,p.producetime,p.warranty")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])->find();
            //$result = array("row" => $list);



            $factory_data = Db::name("factory")->where(['id'=>$list['factory_id']])->find();
            $list['factory_address'] = $factory_data['name']."-".$factory_data['phone']."-".$factory_data['address'];
            $list['factory_tile'] = $factory_data['title'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $pro_time = strtotime($list['producetime'])+$list['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";

                }else{
                    $list['work_bao'] = "过保";

                }
            }else{
                $list['work_bao'] = "在保";

            }
            $this->view->assign("row", $list);
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        $user_shipper_id = $params['user_shipper_id'];
        if(!$user_shipper_id){
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$row['id']])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $user_shipper_code = $params['user_shipper_code'];
        $updata['user_shipper_id'] = $user_shipper_id;
        $updata['user_shipper_name'] = Db::name("shipper")->where(['id'=>$user_shipper_id])->value("name");
        $updata['user_shipper_code'] = $user_shipper_code;
        $updata['image'] = $params['image'];
        $updata['status'] = 4;
        $updata['usersend_time'] = time();

        Db::name("work")->where(['id'=>$row['id']])->update($updata);
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $shipper_data = Db::name("shipper")->where(['id'=>$user_shipper_id])->find();
        $log_content = $admin_data['nickname']."手动上传用户快递单号：".$shipper_data['name'].":".$user_shipper_code;
         $work_data_new = Db::name("work")->where(['id'=>$row['id']])->find();
        \app\common\model\User::workLog($row['id'],$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."手动上传凭证成功",$row['id']);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."手动上传凭证成功",$row['id']);
            \app\admin\model\User::adminnews($work_data['ago_admin_id'],"工单状态变更通知","工单".$product_data['name']."手动上传凭证成功",$row['id']);
        }

        //return "成功";
        $this->success();
        //}
        /*  $result = array("order_id" => $ids);

          return json($result);*/

    }

    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 待手动上传用户快递单号查看
     */
    public function usersendlook($ids=null){
        $list = Db::name("work")->alias('w')
            ->field("w.*,p.code as product_code,p.name as product_name,p.factory_id,p.producetime,p.warranty")
            ->join("product p",'w.product_id = p.id', 'LEFT')
            ->where(['w.id'=>$ids])
            ->find();
        //$result = array("row" => $list);
        //$product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
        $where_r['id'] = $list['factory_id'];
        $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
        //echo Db::name("factory")->getLastSql();
        $list['factory_tile'] = $factory['title'];

        $list['factory_address'] = $factory['name']."-".$factory['phone']."-".$factory['address'];
        $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
        $list['admin_username'] = $admin['username'];
        $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
        $list['channel_name'] = $channel['name'];

        $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];

        $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
        $list['user_shipper_code'] = $user_shipper_name."-".$list['user_shipper_code'];
        $pro_time = strtotime($list['producetime'])+$list['warranty']*86400;
        if($pro_time > time()){
            $list['pro_bao'] = "在保";
        }else{
            $list['pro_bao'] = "过保";
        }

        if($list['is_bao'] == 0){
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $work_time = strtotime($list['real_pay_time'])+365*86400;
            if($work_time > time()){
                $list['work_bao'] = "在保";

            }else{
                $list['work_bao'] = "过保";

            }
        }else{
            $list['work_bao'] = "在保";

        }
        $this->view->assign( 'row', $list);
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }

    /**
     * @param $ids
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 记错
     */
    public function confirmjicuo($ids=null){
        $id = $this->request->post('id');
        $zhuanji = $this->request->post('zhuanji');
        $zhuanji_code = $this->request->post('zhuanji_code');
        $product_id = $this->request->post('product_id');
        $user_shipper_id = $this->request->post('user_shipper_id');
        $user_shipper_code = $this->request->post('user_shipper_code');

        if(!$user_shipper_code){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,p.factory_id,p.producetime,p.warranty")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            $this->view->assign( 'row', $list);
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        $updata['user_shipper_id'] = $user_shipper_id;
        $updata['user_shipper_code'] = $user_shipper_code;
        $product_data = Db::name("product")->where(['id'=>$product_id])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $updata['product_id'] = $product_id;
        $updata['productname_id'] = $product_data['productname_id'];
        $updata['factory_id'] = $product_data['factory_id'];
        Db::name("work")->where(['id'=>$id])->update($updata);
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $log_content = "序列号错误修改";
        $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        $this->success("操作成功");
    }
    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 确认收货
     */
    public function confirm($ids=null){
        $row = $this->model->get($ids);
        $status = $this->request->post('status');
        $id = $this->request->post('id');
        $confirm_time = $this->request->post('confirm_time');
        $zhuanji = $this->request->post('zhuanji');
        $zhuanji_code = $this->request->post('zhuanji_code');
        $product_id = $this->request->post('product_id');
       // echo $zhuanji;exit;
        if (empty($status)) {
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
            $list['user_shipper_code'] = $user_shipper_name.$list['user_shipper_code'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $list['createtime'] = date("Y-m-d H:i:s",$list['createtime']);
            $list['producetime'] = $product['producetime'];
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";

                }else{
                    $list['work_bao'] = "过保";

                }
            }else{
                $list['work_bao'] = "在保";

            }

            $this->view->assign( 'row', $list);
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        // $status = $params['status'];
        //$status = 2;
        if(!$status){
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['confirm_admin'] = $admin_data['username'];

        if($confirm_time){
            $updata['confirm_time'] = strtotime($confirm_time);
        }else{
            $updata['confirm_time'] = time();
        }
        $updata['status'] = $status;


        Db::name("work")->where(['id'=>$id])->update($updata);
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $log_content = "工厂确认收货，检测中";
         $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."已确认收货",$id);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."已确认收货",$id);
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."已确认收货",$id);
        }
        $openid_data = Db::name("openid")->where(['uid'=>$work_data['user_id']])->find();
        if($openid_data){
            $config = get_addon_config('third');

            $appId = $config['wechat']['app_id'];
            $appSecret = $config['wechat']['app_secret'];
            /*$acc_url = "https://api.weixin.qq.com/cgi-bin/token";
            $acc_arr['grant_type'] = "client_credential";
            $acc_arr['appid'] = $appId;
            $acc_arr['secret'] = $appSecret;
            $acc_data = \app\common\model\User::sendCurl(stripslashes($acc_url), $acc_arr, 'get',
                array('User-Agent: Apifox/1.0.0 (https://apifox.com)'));
            $acc_data_arr = json_decode($acc_data,true);*/
            $redis = new \think\cache\driver\Redis(['length' => 3]);
            $token = $redis->get('wechat_access_token');
            if(!$token){
                $acc_url = "https://api.weixin.qq.com/cgi-bin/token";
                $acc_arr['grant_type'] = "client_credential";
                $acc_arr['appid'] = $appId;
                $acc_arr['secret'] = $appSecret;
                $acc_data = \app\common\model\User::sendCurl(stripslashes($acc_url), $acc_arr, 'get',
                    array('User-Agent: Apifox/1.0.0 (https://apifox.com)'));
                $acc_data_arr = json_decode($acc_data,true);
                $token = $acc_data_arr['access_token'];
                $redis->set('wechat_access_token', $token, 7000);
            }
            $factory_data = Db::name("factory")->where(['id'=>$work_data['factory_id']])->find();

            $auth_arr['template_id'] = "co8fttwU1dCEjnQRDNAMKsxj9-fbxORBcL1dnEI-6FM";
            $auth_arr['page'] = "pages/order/detail?id=".$work_data['id'];
            $auth_arr['touser'] = $openid_data['openid'];
            $auth_data['time1']['value'] = date('Y年m月d日 H:i',time());
            $auth_data['thing2']['value'] = $factory_data['address'];
            $auth_data['thing3']['value'] = $factory_data['name'];
            $auth_arr['data'] = $auth_data;
            $auth_arr['miniprogram_state'] = "formal";
            $auth_arr['lang'] = "zh_CN";
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$token;
            $appid_data = \app\common\model\User::sendCurl(stripslashes($url), json_encode($auth_arr,true), 'post',
                array('Content-Type:application/json'));
            Log::write("发送请求信息confirm：".json_encode($auth_arr)."__appid_data:".json_encode($appid_data));
        }
        $this->success("操作成功");
    }
    //确认收货查看
    public function confirmlook($ids=null){
        $row = $this->model->get($ids);
        $status = $this->request->post('status');
        $id = $this->request->post('id');
        if (empty($status)) {
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            $list['createtime'] = date("Y-m-d H:i:s",$list['createtime']);
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
            $list['user_shipper_code'] = $user_shipper_name.$list['user_shipper_code'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];

            if($list['is_bao'] == 0){
                $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";

                }else{
                    $list['work_bao'] = "过保";

                }
            }else{
                $list['work_bao'] = "在保";

            }

            $this->view->assign( 'row', $list);
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        // $status = $params['status'];
        //$status = 2;
        if(!$status){
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['confirm_admin'] = $admin_data['username'];
        $updata['confirm_time'] = time();
        $updata['status'] = $status;
        Db::name("work")->where(['id'=>$id])->update($updata);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."已确认收货",$id);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."已确认收货",$id);
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."已确认收货",$id);
        }

        $this->success("操作成功");
    }
    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 上传检测报告
     */
    public function detection($ids=null){
        $row = $this->model->get($ids);
        $params = $this->request->post('row/a');
        if(!$params['damage_reason']){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,p.producetime,p.warranty")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
            $list['createtime'] = date("Y-m-d H:i:s",$list['createtime']);
            $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
            $list['user_shipper_code'] = $user_shipper_name.$list['user_shipper_code'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                //$product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";
                }else{
                    $list['work_bao'] = "过保";
                }
            }else{
                $list['work_bao'] = "在保";
            }
            $list['confirm_time'] = date('Y-m-d H:i:s',$list['confirm_time']);
            $this->view->assign("row", $list);
            $this->view->assign("ids", $ids);

            return $this->view->fetch();
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        if($params['damage_reason'] == 2){
            $st = 9;
            $confirmdetection_time = time();
            $updata['confirmdetection_time'] = $confirmdetection_time;
        }else{
            $st = 6;
        }

        if(count($params['factory_status']) == 1 && $params['factory_status'][0] == 0){
            //$this->error("维修状态必选");
        }else{
            foreach ($params['factory_status'] as $k=>$v){
                if($v == 0){
                    unset($params['factory_status'][$k]);
                }
            }
        }

        if(count($params['problem']) == 1 && $params['problem'][0] == 0){
            $this->error("问题类型必选");
        }
        foreach ($params['problem'] as $k=>$v){
            if($v == 0){
                unset($params['problem'][$k]);
            }
        }

        $factory_status_str = implode(',',$params['factory_status']);
        $problem_str = implode(',',$params['problem']);
        $problem_status = Db::name("problem")->where(['name'=>'其它','pid'=>0])->where('id','in',$problem_str)->find();
        $problem_status1 = Db::name("problem")->where('name','like','%特殊情况%')->where('id','in',$problem_str)->find();

        $repair_status = Db::name("repair")->where(['name'=>'其它','pid'=>0])->where('id','in',$factory_status_str)->find();
        $repair_status1 = Db::name("repair")->where('name','like','%特殊情况%')->where('id','in',$factory_status_str)->find();
        //echo Db::name("problem")->getLastSql();
       // if(($problem_status || $repair_status) && !$params['problem_content'] && $params['damage_reason'] == 2){
        //var_dump($problem_status);
        //var_dump($repair_status);
        //echo $params['problem_content'] ."_". $params['damage_reason'];
        if(($problem_status || $repair_status || $problem_status1 || $repair_status1) && !$params['problem_content']){
            $this->error("请填写问题描述");
        }

       // var_dump($params['problem']);exit;
        $updata['detection_admin'] = $admin_data['username'];
        $updata['detection_time'] = time();
        $updata['status'] = $st;
        $updata['detection_content'] = $params['detection_content']??'';

        $updata['damage_reason'] = $params['damage_reason']??'';

        $updata['user_content'] = $params['user_content']??'';

        //$updata['cost'] = $params['cost'];
        $updata['cost'] = $params['all_quantity'];
        $updata['real_cost'] = $params['all_quantity_real'];

        $updata['cost_content'] = $params['cost_content']??'';

        $updata['factory_status'] = implode(',', $params['factory_status']);
        $updata['problem_content'] = $params['problem_content']??'';

        $updata['problem'] = implode(',', $params['problem']);
        $work_cost_arr = [];
        //var_dump($params['linedetail']);exit();


        $work_data = Db::name("work")->where(['id'=>$ids])->find();
        if(!$work_data){
            $this->error("数据有误");
        }

        //var_dump($params['linedetail']);
        if(isset($params['linedetail'])){
            foreach ($params['linedetail'] as $k=>$v){
                $w_arr['factory_title'] = $v['factory_title'];
                $w_arr['product_name'] = $v['product_name'];
                $w_arr['costmode_name'] = $v['costmode_name'];
                $w_arr['cost_money'] = $v['cost_money'];
                $w_arr['real_money'] = $v['real_money'];
                $w_arr['work_id'] = $ids;
                $checkbox = $this->request->post('checkbox'.$k);
                if(isset($checkbox) && $checkbox == 'on'){
                    $w_arr['type'] = 1;
                }else{
                    $w_arr['type'] = 0;
                }
                $work_cost_arr[] = $w_arr;
            }
            Db::name("work_cost")->insertAll($work_cost_arr);
        }else{
            $this->error("请选择费用");
        }

        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }

        Db::name("work")->where(['id'=>$ids])->update($updata);

        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();

        $log_content = "工厂上传检测报告，待确认";
         $work_data_new = Db::name("work")->where(['id'=>$ids])->find();

        \app\common\model\User::workLog($ids,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."已上传确认报告",$ids);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","已上传确认报告",$ids);
        }

        $this->success();
    }
    public function sclookdetection($ids=null){
        $list = Db::name("work")->alias('w')
            ->field("w.*,p.code as product_code,p.name as product_name,p.producetime,p.warranty")
            ->join("product p",'w.product_id = p.id', 'LEFT')
            ->where(['w.id'=>$ids])
            ->find();
        //$result = array("row" => $list);
        $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
        $where_r['id'] = $product['factory_id'];
        $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
        //echo Db::name("factory")->getLastSql();
        $list['factory_tile'] = $factory['title'];
        $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
        $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
        $list['admin_username'] = $admin['username'];
        $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
        $list['channel_name'] = $channel['name'];
        $list['confirm_time'] = date('Y-m-d H:i:s',$list['confirm_time']);
        $list['createtime'] = date('Y-m-d H:i:s',$list['createtime']);
        $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
        $list['user_shipper_code'] = $user_shipper_name.$list['user_shipper_code'];
        $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
        $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
        if($pro_time > time()){
            $list['pro_bao'] = "在保";
        }else{
            $list['pro_bao'] = "过保";
        }

        if($list['is_bao'] == 0){
            $work_time = strtotime($list['real_pay_time'])+365*86400;
            if($work_time > time()){
                $list['work_bao'] = "在保";
                //$list['work_bao'] = 1;
            }else{
                $list['work_bao'] = "过保";
                //$list['work_bao'] = 0;
            }
        }else{
            $list['work_bao'] = "在保";
           // $list['work_bao'] = 1;
        }
        $this->view->assign( 'row', $list);
        $this->view->assign("ids", $ids);
        $this->view->assign("damage_reason", $list['damage_reason']);
        return $this->view->fetch();
    }
    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 确认检测结果查看
     */
    public function lookdetection($ids=null){
        $list = Db::name("work")->alias('w')
            ->field("w.*,p.code as product_code,p.name as product_name,p.producetime")
            ->join("product p",'w.product_id = p.id', 'LEFT')
            ->where(['w.id'=>$ids])
            ->find();
        //$result = array("row" => $list);
        $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
        $where_r['id'] = $product['factory_id'];
        $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
        //echo Db::name("factory")->getLastSql();
        $list['factory_tile'] = $factory['title'];
        $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
        $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
        $list['admin_username'] = $admin['username'];
        $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
        $list['channel_name'] = $channel['name'];
        $list['confirmdetection_time'] = date('Y-m-d H:i:s',$list['confirmdetection_time']);
        $list['confirm_time'] = date('Y-m-d H:i:s',$list['confirm_time']);
        $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
        $list['user_shipper_code'] = $user_shipper_name.$list['user_shipper_code'];
        $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];

        $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
        if($pro_time > time()){
            $list['pro_bao'] = "在保";
        }else{
            $list['pro_bao'] = "过保";
        }

        if($list['is_bao'] == 0){
            $work_time = strtotime($list['real_pay_time'])+365*86400;
            if($work_time > time()){
                $list['work_bao'] = "在保";
                //$list['work_bao'] = 1;
            }else{
                $list['work_bao'] = "过保";
                //$list['work_bao'] = 0;
            }
        }else{
            $list['work_bao'] = "在保";
            // $list['work_bao'] = 1;
        }

        $this->view->assign( 'row', $list);
        $this->view->assign("ids", $ids);
        $this->view->assign("damage_reason", $list['damage_reason']);
        return $this->view->fetch();
    }
    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 确认检测结果
     */
    public function confirmdetection($ids=null){
       // $row = $this->model->get($ids);
       // $params = $this->request->post('row/a');
        $status = 7;
        $id = $this->request->post('id');
        $cost = $this->request->post('cost');
        $real_cost = $this->request->post('real_cost');
        $sales_status = $this->request->post('sales_status');
        $cost_content = $this->request->post('cost_content');
        $is_huangou = $this->request->post('is_huangou');
        $confirmdetection_time = $this->request->post('confirmdetection_time');

        if(!$id){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,p.producetime")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            //var_dump($list);
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $list['confirmdetection_time'] = date('Y-m-d H:i:s',$list['confirmdetection_time']);
            $list['confirm_time'] = date('Y-m-d H:i:s',$list['confirm_time']);
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);

            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";
                    //$list['work_bao'] = 1;
                }else{
                    $list['work_bao'] = "过保";
                    //$list['work_bao'] = 0;
                }
            }else{
                $list['work_bao'] = "在保";
                // $list['work_bao'] = 1;
            }
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            $this->view->assign("damage_reason", $list['damage_reason']);

            if($list['confirmdetection_bao_time']){

                $this->view->assign("confirmdetection_bao_time", date('Y-m-d H:i:s',$list['confirmdetection_bao_time']));
            }else{
                $this->view->assign("confirmdetection_bao_time",'');
            }

            return $this->view->fetch();
        }
       // exit;
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['confirmdetection_admin'] = $admin_data['username'];
        if($confirmdetection_time){
            $updata['confirmdetection_time'] = strtotime($confirmdetection_time);
        }else{
            $updata['confirmdetection_time'] = '';
        }

        $updata['status'] = $status;
        $updata['cost'] = $cost;
        $updata['real_cost'] = $real_cost;
        $updata['cost_content'] = $cost_content;
        $updata['sales_status'] = $sales_status;
        $updata['is_huangou'] = $is_huangou;
        if($is_huangou == 1 || $is_huangou == 3){
            $updata['status'] = 10;
        }elseif($is_huangou == 2){
            $updata['status'] = 9;
        }
        $updata['confirmdetection_que_time'] = time();//确认检查报告确认时间
        Db::name("work")->where(['id'=>$id])->update($updata);
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
         $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        if($cost != $work_data['cost']){
            $log_content = $admin_data['nickname']."修改检测结果，费用".$work_data['cost']."->".$cost;
            \app\common\model\User::workLog($id,$log_content,$work_data_new);
        }

        $log_content = $admin_data['nickname']."确认检测结果，待上传凭证";
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."已确认检测结果",$id);
        }

        if($work_data['detection_admin']){
            $detection_admin = Db::name("admin")->where(['username'=>$work_data['detection_admin']])->find();
            \app\admin\model\User::adminnews($detection_admin['id'],"工单状态变更通知","工单".$product_data['name']."已确认检测结果",$id);
        }
        $openid_data = Db::name("openid")->where(['uid'=>$work_data['user_id']])->find();
        if($openid_data){
            $config = get_addon_config('third');

            $appId = $config['wechat']['app_id'];
            $appSecret = $config['wechat']['app_secret'];
           /* $acc_url = "https://api.weixin.qq.com/cgi-bin/token";
            $acc_arr['grant_type'] = "client_credential";
            $acc_arr['appid'] = $appId;
            $acc_arr['secret'] = $appSecret;
            $acc_data = \app\common\model\User::sendCurl(stripslashes($acc_url), $acc_arr, 'get',
                array('User-Agent: Apifox/1.0.0 (https://apifox.com)'));
            $acc_data_arr = json_decode($acc_data,true);*/
            $redis = new \think\cache\driver\Redis(['length' => 3]);
            $token = $redis->get('wechat_access_token');
            if(!$token){
                $acc_url = "https://api.weixin.qq.com/cgi-bin/token";
                $acc_arr['grant_type'] = "client_credential";
                $acc_arr['appid'] = $appId;
                $acc_arr['secret'] = $appSecret;
                $acc_data = \app\common\model\User::sendCurl(stripslashes($acc_url), $acc_arr, 'get',
                    array('User-Agent: Apifox/1.0.0 (https://apifox.com)'));
                $acc_data_arr = json_decode($acc_data,true);
                $token = $acc_data_arr['access_token'];
                $redis->set('wechat_access_token', $token, 7000);
            }

            /*$auth_arr['template_id'] = "EgwoVCxZC2at6XqTeoJqXq5BJnoyp-W_xjwbcAWyd3k";
            $auth_arr['page'] = "pages/order/detail?id=".$work_data['id'];
            $auth_arr['touser'] = $openid_data['openid'];
            $auth_data['time2']['value'] = date('Y年m月d日',time());
            $auth_data['thing3']['value'] = $work_data['problem_content'];
            $auth_arr['data'] = $auth_data;
            $auth_arr['miniprogram_state'] = "trial";
            $auth_arr['lang'] = "zh_CN";*/
            $picdata = Db::name("problem")->where('id','in',$work_data['problem'])->select();
            $pic_image_arr = array_column($picdata, 'name');
            $pic_image_arr_str = implode(',', $pic_image_arr);

            $auth_arr['template_id'] = "UlSvrqNNJGoUeEvg-NM_sgXlEbp7ZtvQqO-MS26zltk";
            $auth_arr['page'] = "pages/order/detail?id=".$work_data['id'];
            $auth_arr['touser'] = $openid_data['openid'];
            $auth_data['amount3']['value'] = $real_cost;
            $auth_data['thing4']['value'] = $pic_image_arr_str;
            $auth_arr['data'] = $auth_data;
            $auth_arr['miniprogram_state'] = "formal";
            $auth_arr['lang'] = "zh_CN";
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$token;
            $appid_data = \app\common\model\User::sendCurl(stripslashes($url), json_encode($auth_arr,true), 'post',
                array('Content-Type:application/json'));
            Log::write("发送请求信息confirmdetection：".json_encode($auth_arr)."__appid_data:".json_encode($appid_data));
        }
        $this->success("操作成功");
    }
    public function confirmdetectionbao($ids=null){
        // $row = $this->model->get($ids);
        // $params = $this->request->post('row/a');
        //$status = 7;
        $id = $this->request->post('id');
        $cost = $this->request->post('cost');
        $real_cost = $this->request->post('real_cost');
        $sales_status = $this->request->post('sales_status');
        $cost_content = $this->request->post('cost_content');
        $is_huangou = $this->request->post('is_huangou');
        $confirmdetection_time = $this->request->post('confirmdetection_time');

        if(!$id){
            $list = Db::name("work")->where(['id'=>$ids])->find();
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            $this->view->assign("damage_reason", $list['damage_reason']);
            return $this->view->fetch();
        }
        // exit;
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['confirmdetection_admin'] = $admin_data['username'];
        $updata['confirmdetection_time'] = strtotime($confirmdetection_time);
        //$updata['status'] = $status;
        $updata['cost'] = $cost;
        $updata['real_cost'] = $real_cost;
        $updata['cost_content'] = $cost_content;
        $updata['sales_status'] = $sales_status;
        $updata['is_huangou'] = $is_huangou;
        $updata['confirmdetection_bao_time'] = time();
        Db::name("work")->where(['id'=>$id])->update($updata);



        $this->success("操作成功");
    }
    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 上传凭证
     */
    public function voucher($ids=null){
        // $row = $this->model->get($ids);
        // $params = $this->request->post('row/a');
        $status = 8;
        $id = $this->request->post('id');
        $voucher = $this->request->post('voucher');
        $cost = $this->request->post('cost');
        $is_voucher = $this->request->post('is_voucher');
        $isstatus = $this->request->post('isstatus');
        $confirmdetection_time = $this->request->post('confirmdetection_time');

        if(!$is_voucher){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,u.username,u.mobile,p.producetime")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->join("user u",'w.user_id = u.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //echo Db::name("work")->getLastSql();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
            $list['admin_type'] = $admin_type;
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
            $list['confirm_time'] = date("Y-m-d H:i:s",$list['confirm_time']);
            if($list['confirmdetection_time']){
                $list['confirmdetection_time'] = date("Y-m-d H:i:s",$list['confirmdetection_time']);
            }else{
                $list['confirmdetection_time'] = '';
            }

            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";
                    //$list['work_bao'] = 1;
                }else{
                    $list['work_bao'] = "过保";
                    //$list['work_bao'] = 0;
                }
            }else{
                $list['work_bao'] = "在保";
                // $list['work_bao'] = 1;
            }
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            $this->view->assign("damage_reason", $list['damage_reason']);
            $this->view->assign("confirmdetection_time", $list['confirmdetection_time']);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        // $updata['detection_admin'] = $admin_data['username'];
        //$updata['detection_time'] = time();
        //var_dump($isstatus);exit;
        if($isstatus == 2){//自动审核
            $status = 9;
        }
        $updata['status'] = $status;
        $updata['voucher'] = $voucher;
        $updata['cost'] = $cost;
        $updata['confirmdetection_time'] = $confirmdetection_time?strtotime($confirmdetection_time):0;
        $updata['voucher_time'] = time();
        Db::name("work")->where(['id'=>$id])->update($updata);
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();

        $log_content = $admin_data['nickname']."手动上传凭证，待审核";
         $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."已上传凭证",$id);
        }
        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."已上传凭证",$id);
        }

        $this->success("操作成功");
    }
    public function voucherlook($ids=null){
        // $row = $this->model->get($ids);
        // $params = $this->request->post('row/a');
        $status = 8;
        $id = $this->request->post('id');
        $voucher = $this->request->post('voucher');
        $cost = $this->request->post('cost');
        $is_voucher = $this->request->post('is_voucher');
        $isstatus = $this->request->post('isstatus');

        if(!$is_voucher){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,u.username,u.mobile,p.producetime")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->join("user u",'w.user_id = u.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //echo Db::name("work")->getLastSql();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
            $list['admin_type'] = $admin_type;
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
            $list['confirm_time'] = date("Y-m-d H:i:s",$list['confirm_time']);
            if($list['confirmdetection_time']){
                $list['confirmdetection_time'] = date("Y-m-d H:i:s",$list['confirmdetection_time']);
            }else{
                $list['confirmdetection_time'] = '';
            }

            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";
                    //$list['work_bao'] = 1;
                }else{
                    $list['work_bao'] = "过保";
                    //$list['work_bao'] = 0;
                }
            }else{
                $list['work_bao'] = "在保";
                // $list['work_bao'] = 1;
            }
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            $this->view->assign("damage_reason", $list['damage_reason']);
            $this->view->assign("confirmdetection_time", $list['confirmdetection_time']);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        // $updata['detection_admin'] = $admin_data['username'];
        //$updata['detection_time'] = time();
        //var_dump($isstatus);exit;
        if($isstatus == 2){//自动审核
            $status = 9;
        }
        $updata['status'] = $status;
        $updata['voucher'] = $voucher;
        $updata['cost'] = $cost;
        $updata['voucher_time'] = time();
        Db::name("work")->where(['id'=>$id])->update($updata);
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();

        $log_content = $admin_data['nickname']."手动上传凭证，待审核";
        $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."已上传凭证",$id);
        }
        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."已上传凭证",$id);
        }

        $this->success("操作成功");
    }
    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 凭证审核和通过
     */
    public function shvoucher($ids=null){
        // $row = $this->model->get($ids);
        // $params = $this->request->post('row/a');
        //$status = 8;
        $status = $this->request->post('status');
        $confirmdetection_time = $this->request->post('confirmdetection_time');
        //var_dump($status);exit;
        $id = $this->request->post('id');
        if(!$status){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,u.username,u.mobile,p.producetime")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->join("user u",'w.user_id = u.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
            $list['confirm_time'] = date("Y-m-d H:i:s",$list['confirm_time']);
            if($list['confirmdetection_time']){
                $list['confirmdetection_time'] = date("Y-m-d H:i:s",$list['confirmdetection_time']);
            }else{
                $list['confirmdetection_time'] = '';
            }
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";
                    //$list['work_bao'] = 1;
                }else{
                    $list['work_bao'] = "过保";
                    //$list['work_bao'] = 0;
                }
            }else{
                $list['work_bao'] = "在保";
                // $list['work_bao'] = 1;
            }
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            $this->view->assign("damage_reason", $list['damage_reason']);
            $this->view->assign("confirmdetection_time",$list['confirmdetection_time']);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['voucher_aud_status'] = $admin_data['username']."-通过";
        $updata['voucher_aud_time'] = time();
        $updata['confirmdetection_time'] = $confirmdetection_time?strtotime($confirmdetection_time):0;
        $updata['status'] = $status;
        Db::name("work")->where(['id'=>$id])->update($updata);
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();

        $log_content = $admin_data['nickname']."审核凭证通过，待工厂寄回";
         $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."凭证审核通过",$id);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."凭证审核通过",$id);
        }

        $this->success("操作成功");
    }
    public function shvoucherlook($ids=null){
        // $row = $this->model->get($ids);
        // $params = $this->request->post('row/a');
        //$status = 8;
        $status = $this->request->post('status');
        //var_dump($status);exit;
        $id = $this->request->post('id');
        if(!$status){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,u.username,u.mobile,p.producetime")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->join("user u",'w.user_id = u.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
            $list['confirm_time'] = date("Y-m-d H:i:s",$list['confirm_time']);
            if($list['confirmdetection_time']){
                $list['confirmdetection_time'] = date("Y-m-d H:i:s",$list['confirmdetection_time']);
            }else{
                $list['confirmdetection_time'] = '';
            }
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";
                    //$list['work_bao'] = 1;
                }else{
                    $list['work_bao'] = "过保";
                    //$list['work_bao'] = 0;
                }
            }else{
                $list['work_bao'] = "在保";
                // $list['work_bao'] = 1;
            }
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            $this->view->assign("damage_reason", $list['damage_reason']);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['voucher_aud_status'] = $admin_data['username']."-通过";
        $updata['voucher_aud_time'] = time();
        $updata['status'] = $status;
        Db::name("work")->where(['id'=>$id])->update($updata);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."凭证审核通过",$id);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."凭证审核通过",$id);
        }

        $this->success("操作成功");
    }
    public function shvoucherbh($ids=null){
        // $row = $this->model->get($ids);
        // $params = $this->request->post('row/a');

       // $id = $this->request->post('id');
        $this->view->assign("ids", $ids);
        return $this->view->fetch();

    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 凭证审核驳回
     */
    public function shvoucherbhsu(){
        // $row = $this->model->get($ids);
        // $params = $this->request->post('row/a');
        $status = 7;
        $id = $this->request->post('id');
        $voucher_re = $this->request->post('voucher_re');
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $updata['voucher_aud_status'] = $admin_data['username']."-驳回";
        $updata['voucher_aud_re_time'] = time();
        $updata['status'] = $status;
        $updata['voucher_re'] = $voucher_re;

        Db::name("work")->where(['id'=>$id])->update($updata);
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();

        $log_content = $admin_data['nickname']."凭证审核驳回";
         $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."凭证审核驳回",$id);
        }

        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."凭证审核驳回",$id);
        }

        //echo Db::name("work")->getLastSql();exit();
        $this->success("操作成功");
    }

    /**
     * @param $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 工厂快递上传
     */
    public function factorysend($ids=null){
        $status = 10;
        $id = $this->request->post('id');
        $admin_shipper_id = $this->request->post('admin_shipper_id');
        $admin_shipper_code = $this->request->post('admin_shipper_code');
        $factorysend_time = $this->request->post('factorysend_time');
        $remarks = $this->request->post('remarks');
        $voucher = $this->request->post('voucher');
        $is_liugc = $this->request->post('is_liugc');
        $gcremarks = $this->request->post('gcremarks');
        $confirmdetection_time = $this->request->post('confirmdetection_time');
        if(!$admin_shipper_id){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,u.username,u.mobile,p.producetime")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->join("user u",'w.user_id = u.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['admin_shipper_id'] = Db::name("admin")->where(['id'=>$this->auth->id])->value("admin_shipper_id");
            $list['factory_tile'] = $factory['title'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            $list['confirm_time'] = date("Y-m-d H:i:s",$list['confirm_time']);
            if($list['confirmdetection_time']){
                $list['confirmdetection_time'] = date("Y-m-d H:i:s",$list['confirmdetection_time']);
            }else{
                $list['confirmdetection_time'] = '';
            }
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";

                }else{
                    $list['work_bao'] = "过保";

                }
            }else{
                $list['work_bao'] = "在保";

            }
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
            $list['createtime'] = date("Y-m-d H:i:s",$list['createtime']);
            if($list['product_name'] == '数据线'){
                $this->view->assign("is_sjx", 1);
            }else{
                $this->view->assign("is_sjx", 0);
            }
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            $this->view->assign("damage_reason", $list['damage_reason']);
            $this->view->assign("confirmdetection_time",$list['confirmdetection_time']);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        // $updata['detection_admin'] = $admin_data['username'];
        //$updata['detection_time'] = time();
        $updata['status'] = $status;
        $updata['admin_shipper_id'] = $admin_shipper_id;
        if($admin_shipper_id == 10000){
            $updata['admin_shipper_name'] = '不用寄出';
            $factorysend_time = date('Y-m-d H:i:s',time());
        }else{
            $updata['admin_shipper_name'] = Db::name("shipper")->where(['id'=>$admin_shipper_id])->value("name");
        }
        $updata['admin_shipper_code'] = $admin_shipper_code;
        $updata['gcremarks'] = $gcremarks;
        if($voucher){
            $updata['voucher'] = $voucher;
        }
        if($remarks) {
            $updata['remarks'] = $remarks;
        }
        $updata['is_liugc'] = $is_liugc;
        $updata['confirmdetection_time'] = $confirmdetection_time?strtotime($confirmdetection_time):0;
        Db::name("admin")->where(['id'=>$this->auth->id])->update(['admin_shipper_id'=>$admin_shipper_id]);
        $updata['factorysend_time'] = strtotime($factorysend_time);
        //工厂总时间
        $gc_z_time = $updata['factorysend_time']-$work_data['confirm_time'];

        //非工厂处理时间
        if($work_data['voucher_aud_time']){
            $f_gc_z_time = $work_data['voucher_aud_time']-$work_data['detection_time'];
        }else{
            $f_gc_z_time = 0;
        }

        //工厂处理时间

        $gc_cl_time = $gc_z_time - $f_gc_z_time;
        //echo $gc_z_time."_".$f_gc_z_time."_".$gc_cl_time;exit;
        $gc_cl_time = sprintf("%.2f", $gc_cl_time/60/60/24);//天

       // var_dump($updata);

        Db::name("work")->where(['id'=>$id])->update($updata);
        $log_content = "工厂寄回".$updata['admin_shipper_name'].":".$admin_shipper_code;
         $work_data_new = Db::name("work")->where(['id'=>$id])->find();
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        $log_content = "已完成订单";
        \app\common\model\User::workLog($id,$log_content,$work_data_new);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."工厂快递上传成功",$id);
        }
        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."工厂快递上传成功",$id);
        }
        $openid_data = Db::name("openid")->where(['uid'=>$work_data['user_id']])->find();
        if($openid_data){
            $config = get_addon_config('third');

            $appId = $config['wechat']['app_id'];
            $appSecret = $config['wechat']['app_secret'];
            $redis = new \think\cache\driver\Redis(['length' => 3]);
            $token = $redis->get('wechat_access_token');
            if(!$token){
                $acc_url = "https://api.weixin.qq.com/cgi-bin/token";
                $acc_arr['grant_type'] = "client_credential";
                $acc_arr['appid'] = $appId;
                $acc_arr['secret'] = $appSecret;
                $acc_data = \app\common\model\User::sendCurl(stripslashes($acc_url), $acc_arr, 'get',
                    array('User-Agent: Apifox/1.0.0 (https://apifox.com)'));
                $acc_data_arr = json_decode($acc_data,true);
                $token = $acc_data_arr['access_token'];
                $redis->set('wechat_access_token', $token, 7000);
            }



           /* $auth_arr['template_id'] = "NQjMt96kG2psYBI5G1LnO3_90kdgPsKlTUUIsZq6x4M";
            $auth_arr['page'] = "pages/order/detail?id=".$work_data['id'];
            $auth_arr['touser'] = $openid_data['openid'];
            $auth_data['character_string4']['value'] = $admin_shipper_code;
            $auth_data['phrase3']['value'] =$updata['admin_shipper_name'];
            $auth_data['thing2']['value'] = $product_data['name'];
            $auth_data['date5']['value'] = date('Y-m-d H:i:s',time());
            $auth_data['thing9']['value'] = "小主，您的快递已经发货啦，请注意查收哦";
            $auth_arr['data'] = $auth_data;
            $auth_arr['miniprogram_state'] = "trial";
            $auth_arr['lang'] = "zh_CN";*/
            $auth_arr['template_id'] = "iYJS98tlU07sXKGpjPcMREuiLvNETw4QGaNbgB4bJrY";
            $auth_arr['page'] = "pages/order/detail?id=".$work_data['id'];
            $auth_arr['touser'] = $openid_data['openid'];
            $auth_data['character_string1']['value'] = $admin_shipper_code;
            $auth_data['time4']['value'] = date('Y-m-d H:i:s',time());
            $auth_arr['data'] = $auth_data;
            $auth_arr['miniprogram_state'] = "formal";
            $auth_arr['lang'] = "zh_CN";
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$token;
            $appid_data = \app\common\model\User::sendCurl(stripslashes($url), json_encode($auth_arr,true), 'post',
                array('Content-Type:application/json'));
            Log::write("发送请求信息factorysend：".json_encode($auth_arr)."__appid_data:".json_encode($appid_data));
        }
        $this->success("操作成功");
    }
    public function factorysendlook($ids=null){
        $status = 10;
        $id = $this->request->post('id');
        $admin_shipper_id = $this->request->post('admin_shipper_id');
        $admin_shipper_code = $this->request->post('admin_shipper_code');
        if(!$admin_shipper_code){
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name,u.username,u.mobile,p.producetime")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->join("user u",'w.user_id = u.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $list['channel_name'] = $channel['name'];
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
            $list['confirm_time'] = date("Y-m-d H:i:s",$list['confirm_time']);
            if($list['confirmdetection_time']){
                $list['confirmdetection_time'] = date("Y-m-d H:i:s",$list['confirmdetection_time']);
            }else{
                $list['confirmdetection_time'] = '';
            }
            if($pro_time > time()){
                $list['pro_bao'] = "在保";
            }else{
                $list['pro_bao'] = "过保";
            }

            if($list['is_bao'] == 0){
                $work_time = strtotime($list['real_pay_time'])+365*86400;
                if($work_time > time()){
                    $list['work_bao'] = "在保";

                }else{
                    $list['work_bao'] = "过保";

                }
            }else{
                $list['work_bao'] = "在保";

            }
            $list['createtime'] = date("Y-m-d H:i:s",$list['createtime']);
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            $this->view->assign("damage_reason", $list['damage_reason']);
            return $this->view->fetch();
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        // $updata['detection_admin'] = $admin_data['username'];
        //$updata['detection_time'] = time();
        $updata['status'] = $status;
        $updata['admin_shipper_id'] = $admin_shipper_id;
        $updata['admin_shipper_code'] = $admin_shipper_code;
        $updata['factorysend_time'] = time();
        Db::name("work")->where(['id'=>$id])->update($updata);
        if($work_data['user_id']){
            \app\admin\model\User::usernews($work_data['user_id'],"工单状态变更通知","您提交的工单".$product_data['name']."工厂快递上传成功",$id);
        }
        if($work_data['admin_id']){
            \app\admin\model\User::adminnews($work_data['admin_id'],"工单状态变更通知","工单".$product_data['name']."工厂快递上传成功",$id);
        }

        $this->success("操作成功");
    }
    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 已完成订单查看
     */
    public function complete($ids=null){
       if(!$ids){
           $ids = $this->request->post('id');
       }
        $complete_remarks = $this->request->post('complete_remarks');
        $gcremarks = $this->request->post('gcremarks');
        $id = $this->request->post('id');
       if(!$id){
           $list = Db::name("work")->alias('w')
               ->field("w.*,p.code as product_code,p.name as product_name,p.producetime")
               ->join("product p",'w.product_id = p.id', 'LEFT')
               ->where(['w.id'=>$ids])
               ->find();
           //echo Db::name("work")->getLastSql();
           //$result = array("row" => $list);
           $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
           $where_r['id'] = $product['factory_id'];
           $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
           //echo Db::name("factory")->getLastSql();
           $list['factory_tile'] = $factory['title'];

           if(isset($list['admin_id']) && $list['admin_id'] > 0){
               $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
               $list['admin_username'] = $admin['username'];
           }

           $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
           $list['channel_name'] = $channel['name'];

           //$admin_shipper_name = Db::name("shipper")->where(['id'=>$list['admin_shipper_id']])->value("name");
           //echo Db::name("shipper")->getLastSql();
           $list['admin_shipper_name'] = $list['admin_shipper_name'];
           $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
           $list['factorysend_time'] = date('Y-m-d',$list['factorysend_time']);
           $list['confirm_time'] = date('Y-m-d H:i:s',$list['confirm_time']);
           $list['confirmdetection_time'] = date('Y-m-d H:i:s',$list['confirmdetection_time']);
           //var_dump($list);
           $user_shipper_name = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->value("name");
           $list['user_shipper_code'] = $user_shipper_name."-".$list['user_shipper_code'];
           $t = time();
           $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
           if($pro_time > $t){
               $list['pro_bao'] = "在保";
           }else{
               $list['pro_bao'] = "过保";
           }
           if($list['pro_bao'] == 0){
               $work_time = strtotime($list['real_pay_time'])+365*86400;
               if($work_time > $t){
                   $list['work_bao'] = "在保";
                   //$list->items()[$k]['work_bao'] = 1;
               }else{
                   $list['work_bao'] = "过保";
                   //$list->items()[$k]['work_bao'] = 0;
               }
           }else{
               $list['work_bao'] = "在保";
               //$list->items()[$k]['work_bao'] = 1;
           }
           $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
           $list['usersend_time'] = date("Y-m-d H:i:s",$list['usersend_time']);
           $this->view->assign("admin_type", $admin_type);
           $this->view->assign( 'row', $list);
           $this->view->assign("ids", $ids);
           $this->view->assign("damage_reason", $list['damage_reason']);
           return $this->view->fetch();
       }
       if($complete_remarks || $gcremarks){
           $work_data = Db::name("work")->where(['id'=>$id])->find();
           if(!$work_data) {
               $this->error("数据有误");
           }
           $updata['complete_remarks'] = $complete_remarks;
           $updata['gcremarks'] = $gcremarks;
           Db::name("work")->where(['id'=>$id])->update($updata);
       }

        $this->success("成功");
    }


    public function import()
    {
        $params = $this->request->post('row/a');
        if($params['file']){
            $params = $this->request->post('row/a');
            //$file = $this->request->request('file');
            $file = $params['file'];
            // exit;
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $hooks = config('addons.hooks');
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!empty($hooks['upload_config_init'])) {
                $third = get_addon_config($hooks['upload_config_init'][0]);

                $remotefile = fopen($third['cdnurl']. $file, 'r');
                $dirpath = dirname($filePath);
                if (!is_dir($dirpath)) {
                    mkdir($dirpath,0777,true);
                }
                $fh = fopen($filePath, 'w');

                while (!feof($remotefile)) {
                    $output = fread($remotefile, 8192);
                    fwrite($fh, $output);
                }
                fclose($remotefile);
            }

            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, 'w');
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding !== 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            $exists = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

                // Log::info($allRow);
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $channel = $currentSheet->getCellByColumnAndRow(1, $currentRow)->getValue();//购买渠道
                    $status = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue();//当前状态
                    $factory_name = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue();//所属工厂
                    $createtime = $currentSheet->getCellByColumnAndRow(4, $currentRow)->getValue();//创建时间
                    $real_pay_time = $currentSheet->getCellByColumnAndRow(5, $currentRow)->getValue();//用户购买时间
                    $order_image = $currentSheet->getCellByColumnAndRow(6, $currentRow)->getValue();//用户购买时间截图
                    $voucher = $currentSheet->getCellByColumnAndRow(7, $currentRow)->getValue();//用户购买时间截图
                    $id = $currentSheet->getCellByColumnAndRow(8, $currentRow)->getValue();//id
                    $confirm_time = $currentSheet->getCellByColumnAndRow(9, $currentRow)->getValue();//确认收货时间
                    $sales_status = $currentSheet->getCellByColumnAndRow(10, $currentRow)->getValue();//售后客服确认维修状态

                    $is_liugc = $currentSheet->getCellByColumnAndRow(11, $currentRow)->getValue();//工厂检查维修状态
                    $cpname = $currentSheet->getCellByColumnAndRow(12, $currentRow)->getValue();// 产品名称
                    $code = $currentSheet->getCellByColumnAndRow(13, $currentRow)->getValue();// 产品序列号
                    $pro_bao = $currentSheet->getCellByColumnAndRow(14, $currentRow)->getValue();//工厂是否在保
                    $is_bao = $currentSheet->getCellByColumnAndRow(15, $currentRow)->getValue();//用户是否在保
                    $res_receiver = $currentSheet->getCellByColumnAndRow(16, $currentRow)->getValue();//收件人姓名
                    $res_mobile = $currentSheet->getCellByColumnAndRow(17, $currentRow)->getValue();//收件人手机号
                    $res_address = $currentSheet->getCellByColumnAndRow(18, $currentRow)->getValue();//收件人地址
                    $user_content = $currentSheet->getCellByColumnAndRow(19, $currentRow)->getValue();//用户说明

                    $user_shipper_code = $currentSheet->getCellByColumnAndRow(20, $currentRow)->getValue();//用户物流单号
                    $jxsfdff = $currentSheet->getCellByColumnAndRow(21, $currentRow)->getValue();//寄修顺丰到付费
                    $fantime = $currentSheet->getCellByColumnAndRow(22, $currentRow)->getValue();//返修时间
                    $remarks = $currentSheet->getCellByColumnAndRow(23, $currentRow)->getValue();//备注
                    $damage_reason = $currentSheet->getCellByColumnAndRow(24, $currentRow)->getValue();//检测类型
                    $detection_content = $currentSheet->getCellByColumnAndRow(25, $currentRow)->getValue();//检测报告
                    $cost_content_sum = $currentSheet->getCellByColumnAndRow(26, $currentRow)->getValue();//费用项
                    $cost = $currentSheet->getCellByColumnAndRow(27, $currentRow)->getValue();//售后费用
                    $cost_content = $currentSheet->getCellByColumnAndRow(28, $currentRow)->getValue();//费用说明

                    $admin_shipper_id = $currentSheet->getCellByColumnAndRow(29, $currentRow)->getValue();//公司物流
                    $admin_shipper_code = $currentSheet->getCellByColumnAndRow(30, $currentRow)->getValue();//公司物流单号

                    $factorysend_time = $currentSheet->getCellByColumnAndRow(31, $currentRow)->getValue();//工厂快递上传时间
                    $gc_cl_time = $currentSheet->getCellByColumnAndRow(32, $currentRow)->getValue();//工厂处理时间
                    $gcremarks = $currentSheet->getCellByColumnAndRow(33, $currentRow)->getValue();//备注2
                    $is_huangou = $currentSheet->getCellByColumnAndRow(34, $currentRow)->getValue();//是否换购
                    $confirmdetection_time = $currentSheet->getCellByColumnAndRow(35, $currentRow)->getValue();//确认检测报告时间
                // echo $confirmdetection_time;
                 // echo $factorysend_time;exit;
                    if (strstr($factorysend_time, '.')) {
                        if($factorysend_time){
                            $factorysend_time = self::excelTime($factorysend_time);
                        }else{
                            $factorysend_time = '';
                        }
                    }
                    if (strstr($confirmdetection_time, '.')) {
                        if($confirmdetection_time){
                            $confirmdetection_time = self::excelTime($confirmdetection_time);
                        }else{
                            $confirmdetection_time = '';
                        }
                    }

                   // echo $factorysend_time;exit;
                   // var_dump($factorysend_time);

/*

                    $xh = $currentSheet->getCellByColumnAndRow(1, $currentRow)->getValue();//xh
                    $sdrq = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue();//sdrq




                    $fan_time = $currentSheet->getCellByColumnAndRow(7, $currentRow)->getValue();//返修时间







                    $admin_shipper_name = $currentSheet->getCellByColumnAndRow(21, $currentRow)->getValue();//公司物流gongsi

                    $problem = $currentSheet->getCellByColumnAndRow(26, $currentRow)->getValue();//问题


                    $complete_remarks = $currentSheet->getCellByColumnAndRow(31, $currentRow)->getValue();//已完成备注

                    $problem_content = $currentSheet->getCellByColumnAndRow(34, $currentRow)->getValue();//问题描述
                    $problem_cost = $currentSheet->getCellByColumnAndRow(35, $currentRow)->getValue();//问题描述
*/

                   /*

                    $usersend_time = $currentSheet->getCellByColumnAndRow(11, $currentRow)->getValue();//用户上传快递时间

                    $shop_name = $currentSheet->getCellByColumnAndRow(13, $currentRow)->getValue();//店铺名称
                    $order_code = $currentSheet->getCellByColumnAndRow(14, $currentRow)->getValue();//订单号
                    $real_pay_time = $currentSheet->getCellByColumnAndRow(15, $currentRow)->getValue();//实际购买时间



                    $reject = $currentSheet->getCellByColumnAndRow(19, $currentRow)->getValue();//驳回原因
                    $reject_time = $currentSheet->getCellByColumnAndRow(20, $currentRow)->getValue();//驳回原因时间
                    $reject_admin = $currentSheet->getCellByColumnAndRow(21, $currentRow)->getValue();//驳回人员
                    $auditing_time= $currentSheet->getCellByColumnAndRow(22, $currentRow)->getValue();//审核时间


                    $damage_reason = $currentSheet->getCellByColumnAndRow(25, $currentRow)->getValue();//损坏原因


                    $problem_content = $currentSheet->getCellByColumnAndRow(28, $currentRow)->getValue();//问题描述

                    $cost_content_sum = $currentSheet->getCellByColumnAndRow(30, $currentRow)->getValue();//费用项

                    $detection_time = $currentSheet->getCellByColumnAndRow(32, $currentRow)->getValue();//检测报告上传时间

                    $confirmdetection_time = $currentSheet->getCellByColumnAndRow(34, $currentRow)->getValue();//确认检测报告时间
                    $confirmdetection_bao_time = $currentSheet->getCellByColumnAndRow(35, $currentRow)->getValue();//确认检查报告保存时间
                    $voucher_time = $currentSheet->getCellByColumnAndRow(37, $currentRow)->getValue();//凭证上传时间
                    $voucher_re = $currentSheet->getCellByColumnAndRow(38, $currentRow)->getValue();//凭证驳回原因
                    $voucher_aud_re_time = $currentSheet->getCellByColumnAndRow(39, $currentRow)->getValue();//凭证审核驳回时间
                    $voucher_aud_time = $currentSheet->getCellByColumnAndRow(40, $currentRow)->getValue();//凭证审核时间
                    $admin_shipper_name = $currentSheet->getCellByColumnAndRow(41, $currentRow)->getValue();//寄出快递公司


                    $is_two = $currentSheet->getCellByColumnAndRow(44, $currentRow)->getValue();//是否二次维修



                    $user_shipper_name = $currentSheet->getCellByColumnAndRow(48, $currentRow)->getValue();//用户寄出快递公司

*/


                    // Log::info('省份城市：'.$provinceCity);
                    $product = Db::name("product")->where(['code'=>$code])->find();
                    if (!$product) {
                        continue;
                    }
                    //$admin = Db::name("admin")->where(['username'=>$admin_name])->find();
                    $channel_data = Db::name("channel")->where(['name'=>$channel])->find();
                    //$factory_id = Db::name("factory")->where(['id'=>$factory_id])->find();
                    /*if($params['isstatus'] == 2){
                        $s = 3;
                    }else{
                        $s = 1;
                    }*/
                    if($is_bao == '是'){
                        $is_bao = 1;
                    }else{
                        $is_bao = 0;
                    }
                    /*if($is_two == '是'){
                        $is_two = 1;
                    }else{
                        $is_two = 0;
                    }
                    if($damage_reason=="非质量问题"){
                        $damage_reason = 1;
                    }elseif($damage_reason=='质量问题'){
                        $damage_reason = 2;
                    }else{
                        $damage_reason = 0;
                    }*/
                    $sales_status_arr = explode('|',$sales_status);
                    $sales_status_sel = Db::name("repair")->where(['name'=>['in',$sales_status_arr]])->select();
                    $sales_status_id = '';
                    foreach ($sales_status_sel as $k=>$v){
                        $sales_status_id .= $v['id'].',';
                    }

//                    $factory_status_arr = explode('|',$factory_status);
//                    //var_dump($factory_status_arr);
//                        $factory_status_sel = Db::name("repair")->where(['name'=>['in',$factory_status_arr]])->select();
//                    //echo Db::name("repair")->getLastSql();
//                    $factory_status_id = '';
//                    foreach ($factory_status_sel as $k=>$v){
//                        $factory_status_id .= $v['id'].',';
//                    }
//var_dump($factory_status_id);

                   // var_dump($problem_id);
                   /* $user_shipper_id = 0;
                    if($user_shipper_name){
                        $user_shipper_id = Db::name("shipper")->where(['name'=>$user_shipper_name])->value("id");
                    }*/
                    /*$admin_shipper_id = 0;
                    $admin_shipper_arr = explode('-',$admin_shipper_code);
                    $admin_shipper_name = $admin_shipper_arr[0];
                    $admin_shipper_code = $admin_shipper_arr[1];
                    if($admin_shipper_name){
                        $admin_shipper_id = Db::name("shipper")->where(['name'=>$admin_shipper_name])->value("id");
                    }*/
                    $admin_shipper_name = $admin_shipper_id;
                    $admin_shipper_id = Db::name("shipper")->where(['name'=>$admin_shipper_id])->value("id");

                    $user_shipper_id = 0;
                    $ueer_shipper_arr = explode('-',$user_shipper_code);
                    $user_shipper_name = $ueer_shipper_arr[0];
                    $user_shipper_code = $ueer_shipper_arr[1];
                    if($user_shipper_name){
                        $user_shipper_id = Db::name("shipper")->where(['name'=>$user_shipper_name])->value("id");
                    }
                   // $damage_reason = '';
                    $problem = '';
                    $problem_id = '';
                    if($damage_reason){
                        $damage_reason_arr = explode('-',$damage_reason);
                        if($damage_reason_arr[0]){
                            $damage_reason = $damage_reason_arr[0];
                            if($damage_reason == '质量问题'){
                                $damage_reason = 2;
                            }elseif($damage_reason == '非质量问题'){
                                $damage_reason = 1;
                            }else{
                                $damage_reason = 0;
                            }
                        }
                        if($damage_reason_arr[1]) {
                            $problem = $damage_reason_arr[1];
                            $problem_arr = explode('|',$problem);
                            // var_dump($problem_arr);
                            $problem_sel = Db::name("problem")->where(['name'=>['in',$problem_arr]])->select();
                            //echo Db::name("repair")->getLastSql();
                            $problem_id = '';
                            foreach ($problem_sel as $k=>$v){
                                $problem_id .= $v['id'].',';
                            }
                            $problem_id = trim($problem_id,',');
                        }

                    }

                    //无,不寄,已寄出,进水待确认,主板坏待确认
                    $status_arr = ['待审核'=>'1','已驳回'=>'2','待用户寄出'=>'3','待工厂收货'=>'4','工厂检测中'=>'5','待确认检查结果'=>'6','待上传凭证'=>'7','凭证待审核'=>'8','待工厂寄出'=>'9','已完成'=>'10','已撤回'=>'11'];
                    $liugc_arr = ['无'=>'0','不寄'=>'1','已寄出'=>'2','待审核寄出'=>'3','进水待确认'=>'4','主板坏待确认'=>'5'];
                    $is_huangou_arr = ['无-修好寄回'=>'0','是，旧笔留工厂'=>'1','否，旧笔寄回'=>'2','否，旧笔留工厂'=>'3','否，需维修'=>'4'];
                    if($problem && $damage_reason != 0 && $status_arr[$status] < 6){
                        $status = '待确认检查结果';
                    }
                    if($admin_shipper_code && $status_arr[$status] < 10){
                        $status = '已完成';
                    }


                    $insert = [
                        // 'confirm_time'=>strtotime($confirm_time),
                        //'user_content'=>$user_content,
                        'sales_status'=>trim($sales_status_id,','),
                        //'factory_status'=>trim($factory_status_id,','),
                        //'gc_cl_time'=> ($gc_cl_time - 25569) * 86400,
                        'is_bao'=>$is_bao,
                        'is_liugc'=>$liugc_arr[$is_liugc],
                        'is_huangou'=>$is_huangou_arr[(string)$is_huangou],
                        'res_receiver'=>$res_receiver,
                        'res_mobile'=>$res_mobile,
                        'res_address'=>$res_address,
                        //  'channel_id'=>$channel_data['id'],
                        'status'=>$status_arr[$status],
                        // 'factory_id'=>$factory_id,
                        //'usersend_time'=>($usersend_time - 25569) * 86400,
                        'confirm_time'=>$confirm_time?strtotime($confirm_time):0,
                        'user_shipper_id'=>$user_shipper_id,
                        'user_shipper_code'=>$user_shipper_code,
                        'admin_shipper_code'=>$admin_shipper_code,
                        'remarks'=>$remarks,
                        'product_id'=>$product['id'],
                        'productname_id'=>$product['productname_id'],
                        'factory_id'=>$product['factory_id'],
                        'channel_id'=>$channel_data['id'],
                        'factorysend_time'=>$factorysend_time?strtotime($factorysend_time):0,
                        'confirmdetection_time'=>$confirmdetection_time?strtotime($confirmdetection_time):0,
                        'real_pay_time'=>$real_pay_time?strtotime($real_pay_time):0,
                        'gc_cl_time'=>$gc_cl_time?strtotime($gc_cl_time):0,
                        'problem'=>$problem_id,
                        'detection_content'=>$detection_content,
                        'cost'=>$cost,
                        'cost_content'=>$cost_content,
                        'gcremarks'=>$gcremarks,
                        //'xh'=>$xh,
                        //'sdrq'=>$sdrq,
                        'jxsfdff'=>$jxsfdff,
                       // 'user_pay_img'=>$user_pay_img,
                        //'problem_content'=>$problem_content,
                        'damage_reason'=>$damage_reason,
                        'admin_shipper_id'=>$admin_shipper_id,
                        'admin_shipper_name'=>$admin_shipper_name,
                        //'real_pay_time'=>$real_pay_time,
                        // 'status'=>$s,
                        // 'createtime'=>time(),
                        'updatetime'=>time(),
                        /*'shop_name'=>$shop_name,
                        'order_code'=>$order_code,
                        'reject'=>$reject,
                        'reject_admin'=>$reject_admin,
                        'damage_reason'=>$damage_reason,
                        'problem_content'=>$problem_content,
                        'cost_content_sum'=>$cost_content_sum,
                        'voucher_re'=>$voucher_re,
                        'admin_shipper_name'=>$admin_shipper_name,
                        'is_two'=>$is_two,
                        'user_shipper_name'=>$user_shipper_name,
                        'user_shipper_id'=>$user_shipper_id,
                        'admin_shipper_id'=>$admin_shipper_id,
                        'reject_time'=>$reject_time?($reject_time - 25569) * 86400:0,
                        'auditing_time'=>$auditing_time?($auditing_time - 25569) * 86400:0,
                        'detection_time'=>$detection_time?($detection_time - 25569) * 86400:0,
                        'confirmdetection_time'=>$confirmdetection_time?($confirmdetection_time - 25569) * 86400:0,
                        'confirmdetection_bao_time'=>$confirmdetection_bao_time?($confirmdetection_bao_time - 25569) * 86400:0,
                        'voucher_time'=>$voucher_time?($voucher_time - 25569) * 86400:0,
                        'voucher_aud_re_time'=>$voucher_aud_re_time?($voucher_aud_re_time - 25569) * 86400:0,
                        'voucher_aud_time'=>$voucher_aud_time?($voucher_aud_time - 25569) * 86400:0,*/
                        //'fan_time'=>$fan_time,
                    ];
                    /*  $code = $currentSheet->getCellByColumnAndRow(1, $currentRow)->getValue();//产品序列号
                      $admin_name = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue();//售后负责人
                      $user_content = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue();//用户说明
                      $channel = $currentSheet->getCellByColumnAndRow(4, $currentRow)->getValue();//渠道
                      // Log::info('省份城市：'.$provinceCity);
                      $product = Db::name("product")->where(['code'=>$code])->find();
                      if (!$product) {
                          continue;
                      }
                      $admin = Db::name("admin")->where(['username'=>$admin_name])->find();
                      $channel_data = Db::name("channel")->where(['name'=>$channel])->find();
                      if($params['isstatus'] == 2){
                          $s = 3;
                      }else{
                          $s = 1;
                      }



                      $insert[] = [
                          'user_content'=>$user_content,
                          'product_id'=>$product['id'],
                          'productname_id'=>$product['productname_id'],
                          'factory_id'=>$product['factory_id'],
                          'channel_id'=>$channel_data['id'],
                          'admin_id'=>$admin['id'],
                          'status'=>$s,
                          'createtime'=>time(),
                          'updatetime'=>time(),
                      ];*/
                    //var_dump($id);
                    //var_dump($insert);
                    if($id){
                        \think\Db::table('fa_work')->where(['id'=>$id])->update($insert);
                    }else{
                        $insert['createtime'] = time();
                        $id = \think\Db::table('fa_work')->insertGetId($insert);
                    }
                    if($cost_content_sum){
                        Db::name("work_cost")->where(['work_id'=>$id])->delete();
                        $problem_cost_arr = explode('|',$cost_content_sum);
                        $cost_money_sum = 0;
                        $real_money_sum = 0;
                        foreach ($problem_cost_arr as $k=>$v){
                            $vv_cost_arr = explode('-',$v);
                            if(!isset($vv_cost_arr[0]) || !isset($vv_cost_arr[1])){
                                $this->error("费用项填写错误");
                            }
                            if(!is_numeric($vv_cost_arr[1])){
                                $this->error("费用项填写错误");
                            }
                            $factory_id = Db::name("factory")->where(['title'=>$factory_name])->value("id");
                            if(!$factory_id){
                                $this->error("费用项工厂错误");
                            }
                            $product_id = Db::name("productname")->where(['name'=>$cpname])->value("id");
                            if(!$product_id){
                                $this->error($cpname."费用项产品错误");
                            }
                            $cost_data = Db::name("cost")->where(['factory_id'=>$factory_id,'product_id'=>$product_id,'cost_name'=>$vv_cost_arr[0],'cost_money'=>$vv_cost_arr[1]])->find();
                            if($cost_data){
                                // var_dump($vv_cost_arr);
                                // $in_data['id'] = $vv_cost_arr[0];
                                $in_data['factory_title'] = $factory_name;
                                $in_data['product_name'] = $cpname;
                                $in_data['costmode_name'] = $vv_cost_arr[0];
                                $in_data['cost_money'] = $vv_cost_arr[1];
                                 $in_data['work_id'] = $id;
                                $in_data['real_money'] = $cost_data['real_money'];
                                $cost_money_sum+=$in_data['cost_money'];
                                 $real_money_sum+=$cost_data['real_money'];

                                Db::name("work_cost")->insertGetId($in_data);
                            }else{
                                $in_data['factory_title'] = $factory_name;
                                $in_data['product_name'] = $cpname;
                                $in_data['costmode_name'] = $vv_cost_arr[0];
                                $in_data['cost_money'] = $vv_cost_arr[1];
                                 $in_data['work_id'] = $id;
                                $in_data['real_money'] = $vv_cost_arr[1];
                                $cost_money_sum+=$in_data['cost_money'];
                                $real_money_sum+=$in_data['cost_money'];

                                Db::name("work_cost")->insertGetId($in_data);
                                $in_work_cost_data['cost_money'] = $vv_cost_arr[1];
                                $in_work_cost_data['cost_name'] = $vv_cost_arr[0];
                                $in_work_cost_data['createtime'] = time();
                                $in_work_cost_data['product_id'] = $product_id;
                                $in_work_cost_data['factory_id'] = $factory_id;
                                $in_work_cost_data['real_money'] = $vv_cost_arr[1];
                                Db::name("cost")->insertGetId($in_work_cost_data);
                            }


                        }
                        Db::name("work")->where(['id'=>$id])->update(['cost'=>$cost_money_sum,'real_cost'=>$real_money_sum]);
                    }
                }
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }
            //var_dump($insert);

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            try {
                //\think\Db::table('fa_work')->insertAll($insert);
            } catch (PDOException $exception) {
                $msg = $exception->getMessage();
                if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                    $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
                };
                $this->error($msg);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }

            $this->success();
        }
        return $this->view->fetch();
    }
    function excelTime($excelTime, $time = false)
    {
        if (!empty($excelTime)) {
            $excelTime = $excelTime;
            $timestamp = (($excelTime - 25569) * 86400);
            $formatDate = date("Y-m-d", $timestamp);
            if ($time) {
                $formatDate = date("Y-m-d H:i:s", $timestamp);
            }
            return $formatDate;
        }
        return $excelTime;
    }

    /**
     * 添加
     */
    public function add()
    {
        $params = $this->request->post('row/a');
        //echo $params['telephone'];exit;
        /*if(isset($params['Product_id'])){
            $user_data = Db::name("user")->where(['mobile'=>$params['mobile']])->find();
            if(!$params['uid'] || empty($params['uid']) || $params['uid'] == "" || !isset($params['uid'])){
                $params['uid'] = 0;
            }
            //file_put_contents('ssss.txt',$params['uid']."_".$user_data['id']);
            if(!$user_data && $params['uid'] == 0){
                if(!$params['real_name']){
                    $this->error("请输入真实姓名");
                }
                $uin_add['Product_id'] = $params['Product_id'];
                $uin_add['image'] = $params['image'];
                $uin_add['user_content'] = $params['user_content'];
                $uin_add['admin_id'] = $params['admin_id'];
                $uin_add['admin_id'] = $params['admin_id'];
                /
                $uin_add['status'] = 'normal';
                //  var_dump($uin_add);exit;
                $user_id = Db::name("user")->insertGetId($uin_add);
                $params['uid'] = $user_id;
            }elseif($params['uid'] == 0 && $user_data){
                if($params['real_name']){
                    $uin_add['username'] = $params['real_name'];
                    Db::name("user")->where(['id'=>$user_data['id']])->update($uin_add);
                }

                $params['uid'] = $user_data['id'];
            }
        }*/
        //echo $this->auth->id;exit;
       // var_dump($params);
        $params['ago_admin_id'] = $this->auth->id;
        if ( $this->request->isPost()) {
            if($this->auth->id){
                $product_data = Db::name("product")->where(['id'=>$params['product_id']])->find();
                if(!$product_data){
                    $this->error("数据有误");
                }
                $uin_add['product_id'] = $params['product_id'];
                $uin_add['productname_id'] = $product_data['productname_id'];
                $uin_add['factory_id'] = $product_data['factory_id'];
                $uin_add['image'] = $params['image']??"";
                $uin_add['user_content'] = $params['user_content'];
                $uin_add['admin_id'] = $params['admin_id']??0;
                $uin_add['channel_id'] = $params['channel_id']??0;
                $uin_add['order_image'] = $params['order_image']??"";
                $uin_add['res_receiver'] = $params['res_receiver'];
                $uin_add['res_mobile'] = $params['res_mobile'];
                $uin_add['res_address'] = $params['res_address'];
                $uin_add['user_shipper_code'] = isset($params['user_shipper_code'])?$params['user_shipper_code']:"";
                $uin_add['shop_name'] = $params['shop_name'];
                $uin_add['order_code'] = $params['order_code'];
                $uin_add['remarks'] = $params['remarks'];
                $uin_add['confirm_time'] = isset($params['confirm_time'])?strtotime($params['confirm_time']):'';
                $uin_add['real_pay_time'] = isset($params['real_pay_time'])?$params['real_pay_time']:'';
                $uin_add['ago_admin_id'] = $this->auth->id;
                //$uin_add['work_bao'] = $work_bao;
                $up_work_data = Db::name("work")->where(['product_id'=>$params['product_id'],'res_mobile'=>$params['res_mobile']])->find();
                if($up_work_data){
                    $uin_add['is_two'] = 1;
                }
                $uin_add['createtime'] = time();

                $product = Db::name("product")->where(['id'=>$params['product_id']])->find();

                if($params['isstatus'] == 2 && $product['name'] != "数据线"){//自动审核通过
                    $uin_add['status'] = 3;
                    $uin_add['isstatus'] = 1;
                }
                if($product['name'] == "数据线"){
                    $cost_money = Db::name("cost")->where(['factory_id'=>$product_data['factory_id'],'product_id'=>$product_data['productname_id']])->value("cost_money");
                    //echo Db::name("cost")->getLastSql();
                    $uin_add['cost'] = $cost_money??0;
                }
                if(isset($params['user_shipper_code']) && $params['user_shipper_code']){
                    $uin_add['status'] = 5;
                }
                if($params['res_mobile']){
                    $fan_data = Db::name("work")->where(['product_id'=>$params['product_id'],'res_mobile'=>$params['res_mobile']])->order('id desc')->find();
                    if($fan_data){
                        $uin_add['fan_time'] = time()-$fan_data['createtime'];
                    }else{
                        $uin_add['fan_time'] = 0;
                    }

                }

                $id = Db::name("work")->insertGetId($uin_add);
                if(isset($params['admin_id'])){
                    $log_content = "工单".$product_data['name']."待审核";

                    \app\common\model\User::workLog($id,$log_content,$uin_add);
                    \app\admin\model\User::adminnews($params['admin_id'],"工单待审核通知","您有工单需要审核请尽快审核",$id);
                }

                $this->success("添加成功");
            }else{
                $this->token();
            }

        }else{
            $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->find();
            $this->view->assign("admin_type", $admin_type['type']);
            $this->view->assign("factory_id", $admin_type['factory_id']);
            return parent::add();
        }
    }
    public function workadmin(){
        $list = Db::name("admin")->where(['type'=>2])->select();
        $re_data['list'] = $list;
        return $re_data;
    }
    public function dr(){

        return $this->view->fetch();
    }
    /**
     * @return void
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
    public function export()
    {
    set_time_limit(0);//设置时间限制
    $ids = $this->request->post('ids'); //获取数据的所有id
    $search = $this->request->post('search'); //获取数据的所有id
    $filter = $this->request->post('filter'); //获取数据的所有id
    $op = $this->request->post('op'); //获取数据的所有id
    $columns = $this->request->post('columns'); //获取数据的所有id

    //var_dump($ids);
    //var_dump($filter);
    ////var_dump($op);
    $filter_arr = json_decode($filter,true);
    $op_arr = json_decode($op,true);
    $where = [];
    foreach ($filter_arr as $k=>$v){
    if($k == 'createtime' || $k == 'confirm_time'){
    $tl = explode(' - ', $v);
    //var_dump($tl);
    $start = strtotime($tl[0]);
    $end = strtotime($tl[1]);
    $where['work.'.$k] = ['between' , "$start,$end"];
    }else{
    if($op_arr[$k] == 'LIKE'){
    $where[$k] = [$op_arr[$k],'%'.$v.'%'];
    }else{
    $where[$k] = [$op_arr[$k],$v];
    }
    }


    }
    //var_dump($where);exit;
    //导出的字段


$field = [
"xh",'sdrq','sales_status','factory_status','id','factorycl_time','fan_time','product>name','product>code',
'is_gq','is_bao','res_receiver','res_mobile','res_address','channel>name','status',
'factory>title','createtime','confirm_time','user_shipper_code','admin_shipper_id',"admin_shipper_code"
,"remarks",'jxsfdff',"factorysend_time","problem",'damage_reason','detection_content','cost','cost_content',
'complete_remarks','real_pay_time','user_pay_img','problem_content','cost_content_sum'
];
    //连表数据需要显示的字段，user>mobile表示为：user表下的mobile字段
$fieldComment = [

'xh' => '序号',//isstatus 借用
'sdrq' => '收到日期',//confirmdetection_que_time 借用
'sales_status' => '客户确认维修状态',
'factory_status' => '工厂维修状态',
'id' => 'id',
'factorycl_time' => '工厂处理时间',
'fan_time' => '二次返修时间',
'product>name' => '产品名称',
'product>code' => '产品序列号',
'is_gq' => '工厂质保状态',
    //工厂质保状态
'is_bao' => '用户质保状态',
'res_receiver' => '用户名',
'res_mobile' => '用户手机号',
'res_address' => '用户地址',
'channel>name' => '购买渠道',
'status' => '当前状态',
'factory>title' => '售后工厂',
'createtime' => '创建时间',
'confirm_time' => '确认收件时间',
    //确认收件时间
'user_shipper_code' => '用户寄出单号',
'admin_shipper_id' => '工厂快递公司',
'admin_shipper_code' => '工厂寄回单号',
'remarks' => '备注',
'jxsfdff' => '寄修顺丰到付费',//zhuanji_code 借用
    //寄修顺丰到付费
'factorysend_time' => '寄出日期',
'problem' => '故障问题',
'damage_reason' => '检测类型',
'detection_content' => '检测结果',
'cost' => '总费用',
'cost_content' => '费用说明',
'complete_remarks' => '已完成备注',
'real_pay_time' => '用户购买时间',
'user_pay_img' => '用户购买时间截图',
'problem_content' => '用户备注',
'cost_content_sum' => '费用项',

];
$fields = $this->getField($field);

$objPHPExcel = new Spreadsheet();
$sheetMain = $objPHPExcel -> getsheet(0);//主sheet
$sheetMain -> setTitle('工单数据');//设置sheet的名称
$sheetMain -> getPageSetup() -> setHorizontalCentered(true);
$sheetMain -> getPageSetup() -> setVerticalCentered(false);


$firstChar = 65;
$tempChar = '';
$tempCharNum = '';
foreach ($fields as $key => &$field) {
    //当列超出 A-Z时，为：AA-AZ,BA-BZ，以此类推
if ($firstChar > 90) {
$firstChar = 65; //当超出 Z 时，重新跳到 A 开始

if ($tempChar == '') {
$tempCharNum = 65;//当超出 Z 时，从 A 开始时需要加上 A-Z
} else {
    $tempCharNum += 1;
}
$tempChar = chr($tempCharNum);
}
$column = chr($firstChar);
$firstChar++;

$char = $tempChar . $column; //哪一列

//处理连表的导出字段
if (is_numeric($field)) {
    $field = [
        'field' => $key,
        'comment' => $fieldComment[$key],
        'type' => 'varchar',
        'chose' => [],
    ];
}
$field['char'] = $char;//记录哪一列，数据循环时可直接取用
//设置表头
$objPHPExcel->getActiveSheet()->setCellValue($char . '1', $field['comment']);
//改变长度
$objPHPExcel->getActiveSheet()->getColumnDimension($char)->setWidth(30);
}
//            halt($fields);

//查询数据
$wheres = [
    // "transport.status" => ['in', '1,2']
];
if ($ids != 'all' && !empty($ids)) {
    $where = [];
    $where['work.id'] = ['in', $ids];
}else{
    //  list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    //$where = [];
    if(isset($where['status'])){

        $where['work.status'] = $where['status'];
        unset($where['status']);
    }
}

//var_dump(json_decode()$where);exit;
$admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
$factory_id = Db::name("admin")->where(['id'=>$this->auth->id])->value("factory_id");
if($admin_type == 1){
    // $where['ago_admin_id'] = $this->auth->id;
    $list = $this->model
        ->with(['Product','User','Channel','Admin','Factory'])
        ->where($where)
        // ->where('ago_admin_id',$this->auth->id)
        //->where('(work.ago_admin_id = '.$this->auth->id.' or work.ago_admin_id IS null)')
        ->select();
}elseif($admin_type == 2){
    //$where['admin_id'] = $this->auth->id;
    $list = $this->model
        ->with(['Product','User','Channel','Admin','Factory'])
        ->where($where)
        ->where("work.status",'not in','11')
        ->select();
}elseif($admin_type == 3){
    //$where['admin_id'] = $this->auth->id;
    $list = $this->model
        ->with(['Product','User','Channel','Admin','Factory'])
        ->where($where)
        ->where('work.factory_id',$factory_id)
        ->where("work.status",'in','4,5,6,7,8,9,10')
        ->select();
}else{
    // var_dump($where);
    $list = $this->model
        ->with(['Product','User','Channel','Admin','Factory'])
        ->where($where)
        ->select();
}
//echo $this->model->getLastSql();exit;
//输出表格
$t = time();
$biaoduanStr = '质量问题,非质量问题';
$problem_list = Db::name("problem")->column("name");
$problem_str = implode(',',$problem_list);
$repair_list = Db::name("repair")->column("name");
$repair_str = implode(',',$repair_list);
// var_dump($problem_list);exit;
$biaoduanStr = '质量问题,非质量问题';
//1待审核2已驳回3待用户寄出4待工厂收货5工厂检测中6待确认检查结果7待上传凭证8凭证待审核9待工厂寄出10已完成
$status_arr = ['1'=>"待审核",'2'=>"已驳回",'3'=>"待用户寄出",'4'=>"待工厂收货",'5'=>"工厂检测中",'6'=>"待确认检查结果",'7'=>"待上传凭证",'8'=>"凭证待审核",'9'=>"待工厂寄出",'10'=>"已完成",'11'=>"撤回",];
foreach ($list as $key => &$val) {


    if($val['status'] == 10){
        //工厂总时间
        $gc_z_time = $val['factorysend_time']-$val['confirm_time'];

        //非工厂处理时间
        if($val['voucher_aud_time']){
            $f_gc_z_time = $val['voucher_aud_time']-$val['detection_time'];
        }else{
            $f_gc_z_time = 0;
        }

        //工厂处理时间

        $gc_cl_time = $gc_z_time - $f_gc_z_time;
        //echo $gc_z_time."_".$f_gc_z_time."_".$gc_cl_time;exit;
        $list[$key]['factorycl_time'] = self::timeToString($gc_cl_time);
    }else{
        $list[$key]['factorycl_time'] = "";
    }

    $list[$key]['status'] = $status_arr[$val['status']];
    if($val['is_bao'] == 0){
        $product = Db::name("product")->where(['id'=>$val['product_id']])->where('deletetime',null)->find();
        $work_time = strtotime($val['real_pay_time'])+365*86400;
        if($work_time > $t){
            $list[$key]['is_bao'] = "在保";
            //$list->items()[$k]['work_bao'] = 1;
        }else{
            $list[$key]['is_bao'] = "过保";
            //$list->items()[$k]['work_bao'] = 0;
        }
    }else{
        $list[$key]['is_bao'] = "在保";
        //$list->items()[$k]['work_bao'] = 1;
    }
    if($val['is_gq'] == 0){
        $list[$key]['is_gq'] = "在保";
    }else{
        $list[$key]['is_gq'] = "过保";
    }
    $val = $val->toArray();
    $i = $key + 2;//表格是从2开始的,第1行为表头
    foreach ($fields as &$field) {
        $data = $val[$field['field']] ?? '';

        //连表显示的字段
        if (strpos($field['field'], '>') !== false) {
            $fieldArr = explode('>', $field['field']);
            //var_dump($fieldArr);
            $data = $val[$fieldArr[0]][$fieldArr[1]];
        }
        //转换为时间格式
        if (is_numeric($data) && mb_strlen($data) == 10) {
            $data = date('Y-m-d H:i:s', $data);
        }
        //设置第行高度
        $objPHPExcel->getActiveSheet()->getRowDimension($key)->setRowHeight(65);
        //将选择项转换成对应的值
        if (!empty($field['chose'])) {
            $data = $field['chose'][$data];
        }
        if($field['field'] == 'damage_reason'){
            if($data==1){
                $data = '非质量问题';
            }elseif($data==2){
                $data = '质量问题';
            }else{
                $data = '';
            }
            // $data = ["非质量问题","质量问题"];
        }
        if($field['field'] == 'admin_shipper_id'){
            $data = Db::name("shipper")->where(['id'=>$val['admin_shipper_id']])->value("name");
        }
        if($field['field'] == 'fan_time'){
            if($data){
                $data = self::timeToString($data);
            }else{
                $data = 0;
            }
        }
        if($field['field'] == 'is_two'){
            if($data==1){
                $data = '是';
            }else{
                $data = '否';
            }

        }


        $cost_str = '';
        if($field['field'] == 'cost_content_sum'){
            $work_costlist = Db::name("work_cost")->where(['work_id'=>$val['id']])->select();
            foreach ($work_costlist as $kk=>$vv){
                $cost_str .= $vv['factory_title'].'-'.$vv['product_name'].'-'.$vv['costmode_name'].'-'.$vv['cost_money'].'-'.$vv['real_money']."|";
            }
            $data = trim($cost_str,'|');
        }
        $bl_str = '';
        if($field['field'] == 'problem'){
            $problemlist = Db::name("problem")->where('id','in',$data)->select();
            foreach ($problemlist as $kk=>$vv){
                $bl_str .= $vv['name'].",";
            }
            $data = trim($bl_str,',');
        }


        //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
        if (strpos($field['type'], 'char') !== false) {
            $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
        } else {
            $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
        }


        $bl_str_status = '';
        if($field['field'] == 'factory_status'){
            $repairlist = Db::name("repair")->where('id','in',$data)->select();
            foreach ($repairlist as $kk=>$vv){
                $bl_str_status .= $vv['name'].",";
            }
            $data = trim($bl_str_status,',');
        }


        //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
        if (strpos($field['type'], 'char') !== false) {
            $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
        } else {
            $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
        }
        $this->setValidation($sheetMain, "AA${i}", '"' . $biaoduanStr . '"');
        $this->setValidation($sheetMain, "D${i}", '"' . $repair_str . '"');
        $this->setValidation($sheetMain, "Z${i}", '"' . $problem_str . '"');
    }
}

$outputFileName = date("YmdHis") . '导出.xlsx';

header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition:inline;filename="' . $outputFileName . '"');
header("Content-Transfer-Encoding: binary");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
$objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
$objWriter->save('php://output');
exit;
}
     */
//导出数据
    public function export()
    {
        set_time_limit(0);//设置时间限制
        $ids = $this->request->post('ids'); //获取数据的所有id
        $search = $this->request->post('search'); //获取数据的所有id
        $filter = $this->request->post('filter'); //获取数据的所有id
        $op = $this->request->post('op'); //获取数据的所有id
        $columns = $this->request->post('columns'); //获取数据的所有id

//var_dump($ids);
//var_dump($filter);
////var_dump($op);
        $filter_arr = json_decode($filter,true);
        $op_arr = json_decode($op,true);
        $where = [];
        foreach ($filter_arr as $k=>$v){
            if($k == 'createtime' || $k == 'confirm_time' || $k == 'confirmdetection_time'|| $k == 'factorysend_time'){
                $tl = explode(' - ', $v);
                //var_dump($tl);
                $start = strtotime($tl[0]);
                $end = strtotime($tl[1]);
                $where['work.'.$k] = ['between' , "$start,$end"];
            }else{
                if($op_arr[$k] == 'LIKE'){
                    $where[$k] = [$op_arr[$k],'%'.$v.'%'];
                }else{
                    $where[$k] = [$op_arr[$k],$v];
                }
            }


        }
        //var_dump($where);exit;
        //导出的字段

       /* $field = [
            'confirm_time','sales_status','createtime','factory_status','id','product>name','product>code','product>producetime','factory>title','res_receiver','res_mobile','res_address','user_content','user_shipper_code','usersend_time','channel>name','shop_name','order_code',"real_pay_time","is_bao",'remarks',"status","reject","reject_time","reject_admin",'auditing_time','confirm_time','detection_content','damage_reason','problem','problem_content','cost_content','cost_content_sum','cost', 'detection_time','confirmdetection_time','confirmdetection_bao_time','confirmdetection_que_time','voucher_time','voucher_re','voucher_aud_re_time','voucher_aud_time','admin_shipper_name', 'admin_shipper_code','factorysend_time','is_two','factorycl_time','fan_time','complete_remarks','user_shipper_name'
        ];*/
        /*$field = [
            'confirm_time','sales_status','createtime','factory_status','id','product>name','product>code','factory>title','res_receiver','res_mobile','res_address','user_content','user_shipper_code','usersend_time','channel>name','shop_name','order_code',"real_pay_time","is_bao",'remarks',"status","reject",'auditing_time','confirm_time','detection_content','damage_reason','problem','problem_content','cost_content','cost', 'detection_time','confirmdetection_time','confirmdetection_bao_time','voucher_time','voucher_re','voucher_aud_re_time','voucher_aud_time', 'admin_shipper_code','factorysend_time','is_two','factorycl_time','fan_time','complete_remarks'
        ];*/
        $field = [
            'channel>name','status','factory>title','createtime','real_pay_time','order_image','voucher',
            'id','confirm_time','sales_status','is_liugc','product>name','product>code','is_gq','is_bao',
            'res_receiver','res_mobile','res_address','user_content','user_shipper_code','jxsfdff','fan_time',
            "remarks",'problem','detection_content','cost_content_sum','cost','cost_content',"admin_shipper_id","admin_shipper_code"
            ,'factorysend_time','factorycl_time','gcremarks','is_huangou','confirmdetection_time'
        ];
        //连表数据需要显示的字段，user>mobile表示为：user表下的mobile字段
        $fieldComment = [
            'id' => '系统工单号',
            'factorycl_time' => '工厂处理时间',
            'fan_time' => '二次返修时间',
            'product>name' => '产品名称',
            'product>code' => '产品序列号',
            'is_gq' => '工厂质保状态',
            //工厂质保状态
            'is_bao' => '用户质保状态',
            'res_receiver' => '用户名',
            'res_mobile' => '用户电话',
            'res_address' => '用户地址',
            'channel>name' => '购买渠道',
            'status' => '当前状态',
            'factory>title' => '售后工厂',
            'createtime' => '创建时间',
            'real_pay_time' => '用户购买时间',
            'user_pay_img' => '用户购买时间截图',
            'order_image' => '支付截图',
            'confirm_time' => '确认收件时间',
            //确认收件时间
            'user_shipper_code' => '用户寄出单号',
            'admin_shipper_id' => '工厂寄回快点公司',
            'admin_shipper_code' => '工厂寄回单号',
            'remarks' => '备注',
            'jxsfdff' => '寄修顺丰到付费',//zhuanji_code 借用
            'factorysend_time' => '寄出日期',
            'user_content' => '用户说明',

            'problem' => '检测类型',
            'detection_content' => '检测结果',
            'cost' => '总费用',
            'cost_content' => '费用说明',
            'complete_remarks' => '已完成备注',
            'work_bao' => '用户质保状态',
            'gcremarks' => '备注2',
            'is_huangou' => '是否换购',
            'confirmdetection_time' => '确认检测报告时间',
            'cost_content_sum' => "费用项 （费用名称-费用（多项用|隔开）\n 例如：人工-5.00|笔头-18.00）",


           // 'admin_shipper_id' => '工厂快递公司',



            //寄修顺丰到付费

           // 'problem' => '故障问题',
            /* 'xh' => '序号',//isstatus 借用
                       'sdrq' => '收到日期',//confirmdetection_que_time 借用
                       'sales_status' => '客户确认维修状态',
                       'factory_status' => '工厂维修状态',*/


           // 'problem_content' => '用户备注',
           // 'cost_content_sum' => '费用项',

            /*'usersend_time' => '用户寄出时间',



            'product>producetime' => '生产日期',


            'user_content' => '用户说明',


            'shop_name' => '店铺名称',
            'order_code' => '订单编号',
            'real_pay_time' => '实际购买时间',



            'reject' => '驳回原因',
            'reject_time' => '驳回原因时间',
            'reject_admin' => '驳回人员',
            'auditing_time' => '审核通过时间',



            'confirm_time' => '工厂确认收货时间',
            'detection_content' => '检测报告',

            'damage_reason' => '损坏原因',

            'problem' => '问题类型',
            'problem_content' => '问题描述',
            'cost_content' => '费用说明',
            'cost_content_sum' => '费用项',
            'cost' => '售后费用',


            'detection_time' => '上传检测结果时间',

            'confirmdetection_time' => '确认检测结果时间',
            'confirmdetection_bao_time' => '确认检测结果-保存时间',
            'confirmdetection_que_time' => '确认检测结果-确认时间',
            'voucher_time' => '手动上传凭证时间',
            'voucher_re' => '凭证驳回原因',
            'voucher_aud_re_time' => '凭证驳回原因时间',
            'voucher_aud_time' => '凭证审核通过时间',
            'admin_shipper_name' => '寄出快递公司',
            'factorysend_time' => '寄回时间',
            'is_two' => '是否二次维修',


            'complete_remarks' => '已完成备注',
            'user_shipper_name' => '用户寄出快递公司',*/
        ];
        $fields = $this->getField($field);

        $objPHPExcel = new Spreadsheet();
        $sheetMain = $objPHPExcel -> getsheet(0);//主sheet
        $sheetMain -> setTitle('工单数据');//设置sheet的名称
        $sheetMain -> getPageSetup() -> setHorizontalCentered(true);
        $sheetMain -> getPageSetup() -> setVerticalCentered(false);

       /* foreach ($fieldComment as $key => $value) {
            $sheetMain -> setCellValue($key, $value);
        }*/
        $firstChar = 65;
        $tempChar = '';
        $tempCharNum = '';
        foreach ($fields as $key => &$field) {
            //当列超出 A-Z时，为：AA-AZ,BA-BZ，以此类推
            if ($firstChar > 90) {
                $firstChar = 65; //当超出 Z 时，重新跳到 A 开始

                if ($tempChar == '') {
                    $tempCharNum = 65;//当超出 Z 时，从 A 开始时需要加上 A-Z
                } else {
                    $tempCharNum += 1;
                }
                $tempChar = chr($tempCharNum);
            }
            $column = chr($firstChar);
            $firstChar++;

            $char = $tempChar . $column; //哪一列

            //处理连表的导出字段
            if (is_numeric($field)) {
                $field = [
                    'field' => $key,
                    'comment' => $fieldComment[$key],
                    'type' => 'varchar',
                    'chose' => [],
                ];
            }
            $field['char'] = $char;//记录哪一列，数据循环时可直接取用
            //设置表头
            $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $field['comment']);
            //改变长度
            $objPHPExcel->getActiveSheet()->getColumnDimension($char)->setWidth(30);
        }
//            halt($fields);

        //查询数据
        $wheres = [
           // "transport.status" => ['in', '1,2']
        ];
        if ($ids != 'all' && !empty($ids)) {
            $where = [];
            $where['work.id'] = ['in', $ids];
        }else{
          //  list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //$where = [];
            if(isset($where['status'])){

                $where['work.status'] = $where['status'];
                unset($where['status']);
            }
        }
        //var_dump($where);exit;
       /* var_dump($where);
        //var_dump($where);exit;
        $list = $this->model
            ->with(['Product','User','Channel','Admin','Factory'])
            //->where($wheres)
            ->where($where)
            ->select();
        echo $this->model->getLastSql();exit;*/
        //var_dump(json_decode()$where);exit;
        $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
        $factory_id = Db::name("admin")->where(['id'=>$this->auth->id])->value("factory_id");
        if($admin_type == 1){
            // $where['ago_admin_id'] = $this->auth->id;
            $list = $this->model
                ->with(['Product','User','Channel','Admin','Factory'])
                ->where($where)
                // ->where('ago_admin_id',$this->auth->id)
                //->where('(work.ago_admin_id = '.$this->auth->id.' or work.ago_admin_id IS null)')
                ->select();
        }elseif($admin_type == 2){
            //$where['admin_id'] = $this->auth->id;
            $list = $this->model
                ->with(['Product','User','Channel','Admin','Factory'])
                ->where($where)
                ->where("work.status",'not in','11')
                ->select();
        }elseif($admin_type == 3){
            //$where['admin_id'] = $this->auth->id;
            $list = $this->model
                ->with(['Product','User','Channel','Admin','Factory'])
                ->where($where)
                ->where('work.factory_id',$factory_id)
                ->where("work.status",'in','4,5,6,7,8,9,10')
                ->select();
        }else{
            //var_dump($where);exit;
            $list = $this->model
                ->with(['Product','User','Channel','Admin','Factory'])
                ->where($where)
                ->select();
        }
        //echo $this->model->getLastSql();exit;
        //输出表格
        $t = time();
        $biaoduanStr = '质量问题,非质量问题';
        //$problem_list = Db::name("problem")->column("name");
        $problem_list = Db::name("problem")->where(['pid'=>['>',0]])->select();
        //echo Db::name("problem")->getLastSql();
        $problem_pid_id = Db::name("problem")->where(['pid'=>0,'name'=>'非质量问题'])->value("id");
        //echo Db::name("problem")->getLastSql();exit;
        $problem_str = '';
        foreach ($problem_list as $k=>$v){
            if($v['pid'] == $problem_pid_id){
                $problem_str .= "非质量问题-".$v['name'].',';
            }else{
                $problem_str .= "质量问题-".$v['name'].',';
            }
        }
        $problem_str = trim($problem_str,',');
        //$problem_str = implode(',',$problem_str);
        $repair_list = Db::name("repair")->column("name");
        $repair_str = implode(',',$repair_list);
       // var_dump($problem_list);exit;
        $biaoduanStr = '质量问题,非质量问题';
        $is_liugcStr = '无,不寄,已寄出,待审核寄出,进水待确认,主板坏待确认';
        $is_huangou = ['0'=>'无-修好寄回','1'=>'是，旧笔留工厂','2'=>'否，旧笔寄回','3'=>'否，旧笔留工厂','4'=>'否，需维修'];
        $is_huangou_str = implode(',',$is_huangou);
        $jxsfdffStr = '否,是';
        //1待审核2已驳回3待用户寄出4待工厂收货5工厂检测中6待确认检查结果7待上传凭证8凭证待审核9待工厂寄出10已完成
        $status_arr = ['1'=>"待审核",'2'=>"已驳回",'3'=>"待用户寄出",'4'=>"待工厂收货",'5'=>"工厂检测中",'6'=>"待确认检查结果",'7'=>"待上传凭证",'8'=>"凭证待审核",'9'=>"待工厂寄出",'10'=>"已完成",'11'=>"撤回",];
        $status_arr_str = implode(',',$status_arr);
        //var_dump($list);exit;
        foreach ($list as $key => &$val) {

            //var_dump($val['damage_reason']);exit;
            //$list[$key]['user_shipper_name'] = Db::name("shipper")->where(['id'=>$val['user_shipper_id']])->value("name");
           /* $list[$key]['isstatus'] = "";
            $list[$key]['confirmdetection_que_time'] = '';
            $list[$key]['zhuanji_code'] = '';
            $list[$key]['cost_content_sum'] = '';*/
           // $list[$key]['admin_shipper_name'] = Db::name("shipper")->where(['id'=>$val['admin_shipper_id']])->value("name");



            if($val['status'] == 10){
                //工厂总时间
                $gc_z_time = $val['factorysend_time']-$val['confirm_time'];

                //非工厂处理时间
                if($val['voucher_aud_time']){
                    $f_gc_z_time = $val['voucher_aud_time']-$val['detection_time'];
                }else{
                    $f_gc_z_time = 0;
                }

                //工厂处理时间

                $gc_cl_time = $gc_z_time - $f_gc_z_time;
                //echo $gc_z_time."_".$f_gc_z_time."_".$gc_cl_time;exit;
                $list[$key]['factorycl_time'] = self::timeToString($gc_cl_time);
            }else{
                $list[$key]['factorycl_time'] = "";
            }

            $list[$key]['status'] = $status_arr[$val['status']];
            $list[$key]['is_huangou'] = $is_huangou[$val['is_huangou']];
            if($val['is_bao'] == 0){
                $product = Db::name("product")->where(['id'=>$val['product_id']])->where('deletetime',null)->find();
                $work_time = strtotime($val['real_pay_time'])+365*86400;
                if($work_time > $t){
                    $list[$key]['is_bao'] = "在保";
                    //$list->items()[$k]['work_bao'] = 1;
                }else{
                    $list[$key]['is_bao'] = "过保";
                    //$list->items()[$k]['work_bao'] = 0;
                }
            }else{
                $list[$key]['is_bao'] = "在保";
                //$list->items()[$k]['work_bao'] = 1;
            }
           /* if($val['is_gq'] == 0){
                $list[$key]['is_gq'] = "在保";
            }else{
                $list[$key]['is_gq'] = "过保";
            }*/
            $product = Db::name("product")->where(['id'=>$val['product_id']])->where('deletetime',null)->find();
            $pro_time = strtotime($product['producetime'])+$product['warranty']*86400;
            if($pro_time > $t){
                $list[$key]['is_gq'] = "在保";
            }else{
                $list[$key]['is_gq'] = "过保";
            }

            if($val['is_liugc'] == 2){
                $list[$key]['is_liugc'] = "已寄出";
            }elseif($val['is_liugc'] == 1){
                $list[$key]['is_liugc'] = "不寄";
            }elseif($val['is_liugc'] == 3){
                $list[$key]['is_liugc'] = "待审核寄出";
            }elseif($val['is_liugc'] == 4){
                $list[$key]['is_liugc'] = "进水待确认";
            }elseif($val['is_liugc'] == 5){
                $list[$key]['is_liugc'] = "主板坏待确认";
            }else{
                $list[$key]['is_liugc'] = "无";
            }
            $val = $val->toArray();
            $i = $key + 2;//表格是从2开始的,第1行为表头
            foreach ($fields as &$field) {
                $data = $val[$field['field']] ?? '';

                //连表显示的字段
                if (strpos($field['field'], '>') !== false) {
                    $fieldArr = explode('>', $field['field']);
                   //var_dump($fieldArr);
                    $data = $val[$fieldArr[0]][$fieldArr[1]];
                }
                //转换为时间格式
                if (is_numeric($data) && mb_strlen($data) == 10) {
                    $data = date('Y-m-d H:i:s', $data);
                }
                //设置第行高度
                $objPHPExcel->getActiveSheet()->getRowDimension($key)->setRowHeight(65);
                //将选择项转换成对应的值
                if (!empty($field['chose'])) {
                    $data = $field['chose'][$data];
                }
                if($field['field'] == 'damage_reason'){
                    if($data==1){
                        $data = '非质量问题';
                    }elseif($data==2){
                        $data = '质量问题';
                    }else{
                        $data = '';
                    }
                   // $data = ["非质量问题","质量问题"];
                }
                if($field['field'] == 'admin_shipper_id'){
                    $data = Db::name("shipper")->where(['id'=>$val['admin_shipper_id']])->value("name");
                   // unset($val['admin_shipper_id']);
                }
                if($field['field'] == 'user_shipper_code'){
                    $data = Db::name("shipper")->where(['id'=>$val['user_shipper_id']])->value("name").'-'.$val['user_shipper_code'];
                    unset($val['user_shipper_id']);
                }
                if($field['field'] == 'fan_time'){
                    if($data){
                        $data = self::timeToString($data);
                    }else{
                        $data = 0;
                    }
                }
                if($field['field'] == 'is_two'){
                    if($data==1){
                        $data = '是';
                    }else{
                        $data = '否';
                    }

                }
              /*  if($field['field'] == 'damage_reason'){
                    if($data==1){
                        $data = '非质量问题';
                    }else{
                        $data = '质量问题';
                    }

                }*/
              /*  if($field['field'] == 'jxsfdff'){
                    if($data==1){
                        $data = '是';
                    }else{
                        $data = '否';
                    }

                }*/
                //工厂名称-产品名称-费用名称-费用（多想用｜隔开）
                $cost_str = '';
                if($field['field'] == 'cost_content_sum'){
                    $work_costlist = Db::name("work_cost")->where(['work_id'=>$val['id']])->select();
                    foreach ($work_costlist as $kk=>$vv){
                        $cost_str .= $vv['costmode_name'].'-'.$vv['cost_money']."|";
                    }
                    $data = trim($cost_str,'|');
                }
                $bl_str = '';
                if($field['field'] == 'problem'){
                    $problemlist = Db::name("problem")->where('id','in',$data)->select();
                    foreach ($problemlist as $kk=>$vv){
                        if($vv['type'] == 1){
                            $bl_str .= "质量问题-".$vv['name'].",";
                        }else{
                            $bl_str .= "非质量问题-".$vv['name'].",";
                        }

                    }
                    $data = trim($bl_str,',');
                }


                //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
                if (strpos($field['type'], 'char') !== false) {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
                }


                $bl_str_status = '';
                if($field['field'] == 'factory_status'){
                    $repairlist = Db::name("repair")->where('id','in',$data)->select();
                    foreach ($repairlist as $kk=>$vv){
                        $bl_str_status .= $vv['name'].",";
                    }
                    $data = trim($bl_str_status,',');
                }


                //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
                if (strpos($field['type'], 'char') !== false) {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
                }
                $this->setValidation($sheetMain, "B${i}", '"' . $status_arr_str . '"');
                $this->setValidation($sheetMain, "X${i}", '"' . $problem_str . '"');
                $this->setValidation($sheetMain, "K${i}", '"' . $is_liugcStr . '"');
                $this->setValidation($sheetMain, "AH${i}", '"' . $is_huangou_str . '"');
                //$this->setValidation($sheetMain, "U${i}", '"' . $jxsfdffStr . '"');
                //$this->setValidation($sheetMain, "K${i}", '"' . $repair_str . '"');
                //$this->setValidation($sheetMain, "Z${i}", '"' . $problem_str . '"');
            }
        }

        $outputFileName = date("YmdHis") . '导出.xlsx';

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $outputFileName . '"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $objWriter->save('php://output');
        exit;
    }
    /**
     * 设置某个单元格的下拉列表规则
     * @param Worksheet $sheet
     * @param [string] $cellPoint 单元格坐标. A1
     * @param [sting] $format 公式
     * @return void
     */
    protected function setValidation(Worksheet $sheet, $cellPoint, $format)
    {
        $validation = $sheet -> getCell($cellPoint) -> getDataValidation();
        $validation -> setType(DataValidation::TYPE_LIST);
        $validation -> setErrorStyle(DataValidation::STYLE_INFORMATION);
        $validation -> setAllowBlank(false);
        $validation -> setShowInputMessage(true);
        $validation -> setShowErrorMessage(true);
        $validation -> setShowDropDown(true);

        $validation -> setErrorTitle('输出错误');
        $validation -> setError('值不在列表中');
        $validation -> setPromptTitle('请选择');
        $validation -> setPrompt('请从列表中选择一个值');
        $validation -> setFormula1($format);
        // $validation->setFormula1('=major');//使用某个公式
        // $validation->setFormula1('"A1,A2,A3"');//可以直接写列表，用逗号分隔,最多255字符
        // $objValidation->setFormula1('=INDIRECT(F5)');//indirect间接的，以某个坐标为依托，联级
    }

    /**
     * 设置某个单元格的输入规则
     * @param Worksheet $sheet
     * @param [string] $cellPoint 单元格坐标. A1
     * @param [sting] type 输入类型 DataValidation::TYPE_LIST
     * @return void
     */
    protected function setInputRule(Worksheet $sheet, $cellPoint, $type)
    {
        $validation = $sheet -> getCell($cellPoint) -> getDataValidation();
        $validation -> setType($type);
        $validation -> setErrorStyle(DataValidation::STYLE_INFORMATION); //输错了的话显示的提示属于哪个级别
        $validation -> setAllowBlank(false);
        $validation -> setShowInputMessage(true);
        $validation -> setShowErrorMessage(true);
        $validation -> setErrorTitle('输入格式有误');
    }
//导出数据
public function logexport()
{
    set_time_limit(0);//设置时间限制
    $ids = $this->request->post('ids'); //获取数据的所有id
    $search = $this->request->post('search'); //获取数据的所有id
    $filter = $this->request->post('filter'); //获取数据的所有id
    $op = $this->request->post('op'); //获取数据的所有id
    $columns = $this->request->post('columns'); //获取数据的所有id

//var_dump($ids);
//var_dump($filter);
////var_dump($op);
    $filter_arr = json_decode($filter,true);
    $op_arr = json_decode($op,true);
    $where = [];
    foreach ($filter_arr as $k=>$v){
        if($op_arr[$k] == 'LIKE'){
            $where[$k] = [$op_arr[$k],'%'.$v.'%'];
        }else{
            $where[$k] = [$op_arr[$k],$v];
        }

    }
    //var_dump($where);
//exit;
    //导出的字段
    /*$field = [
       'res_address','channel->name',"real_pay_time","status","admin->nickname","reject","reject_time",'admin_shipper_name','admin_shipper_code','usersend_time',"auditing_time",'confirm_time','problem'.'cost','factory_status','cost_content', 'detection_time','sales_status','confirmdetection_time','voucher_time','voucher_re','voucher_aud_re_time','voucher_aud_time','user>nickname', 'user>mobile', 'confirm_time','image'
    ];*/
    $field = [
        'work_log>id','factory>title','product>name','product>code','work_log>res_receiver','work_log>res_mobile','work_log>res_address','work_log>problem','channel>name','work_log>shop_name','work_log>order_code',"work_log>real_pay_time","work_log>is_bao","work_log>content","work_log>reject","work_log>reject_time","work_log>reject_admin",'work_log>auditing_time','work_log>user_shipper_code','work_log>usersend_time','work_log>confirm_time','work_log>detection_content','work_log>damage_reason','work_log>factory_status','work_log>problem_content','work_log>cost_content','work_log>cost_content_sum','work_log>cost', 'work_log>detection_time','work_log>sales_status','confirmdetection_time','work_log>confirmdetection_bao_time','work_log>confirmdetection_que_time','work_log>voucher_time','work_log>voucher_re','work_log>voucher_aud_re_time','work_log>voucher_aud_time','work_log>admin_shipper_name', 'work_log>admin_shipper_code','work_log>factorysend_time'
    ];
    //连表数据需要显示的字段，user>mobile表示为：user表下的mobile字段
    $fieldComment = [
        'work_log>id' => 'Id',
        'factory>title' => '所属工厂',
        'product>name' => '产品名称',
        'product>code' => '产品序列号',
        'work_log>res_receiver' => '用户名',
        'work_log>res_mobile' => '用户手机号',
        'work_log>res_address' => '用户地址',
        'work_log>problem' => '故障问题',
        'channel>name' => '购买渠道',
        'work_log>shop_name' => '店铺名称',
        'work_log>order_code' => '订单编号',
        'work_log>real_pay_time' => '实际购买时间',
        'work_log>is_bao' => '用户是否在保',
        'work_log>content' => '状态',
        'work_log>reject' => '驳回原因',
        'work_log>reject_time' => '驳回时间',
        'work_log>reject_admin' => '驳回人员',
        'work_log>auditing_time' => '审核通过时间',
        'work_log>user_shipper_id' => '用户寄出快递公司',
       /* 'work_log>user_shipper_name' => '用户寄出快递公司',*/
        'work_log>user_shipper_code' => '用户寄出单号',
        'work_log>usersend_time' => '用户寄出时间',
        'work_log>confirm_time' => '工厂确认收货时间',
        'work_log>detection_content' => '检测报告',

        'work_log>damage_reason' => '损坏原因',
        'work_log>factory_status' => '工厂检测维修状态',
        'work_log>problem_content' => '用户备注',
        'work_log>cost_content' => '费用说明',
        'work_log>cost_content_sum' => '费用项',
        'work_log>cost' => '售后费用',


        'work_log>detection_time' => '上传检测结果时间',
        'work_log>sales_status' => '售后客服确认维修状态',
        'work_log>confirmdetection_time' => '确认检测结果时间',
        'work_log>confirmdetection_bao_time' => '确认检测结果-保存时间',
        'work_log>confirmdetection_que_time' => '确认检测结果-确认时间',
        'work_log>voucher_time' => '手动上传凭证时间',
        'work_log>voucher_re' => '凭证驳回原因',
        'work_log>voucher_aud_re_time' => '凭证驳回原因时间',
        'work_log>voucher_aud_time' => '凭证审核通过时间',
        'work_log>admin_shipper_name' => '寄出快递公司',
        'work_log>admin_shipper_code' => '物流单号',
        'work_log>factorysend_time' => '寄回时间',
    ];
    $fields = $this->getField($field);

    $objPHPExcel = new Spreadsheet();
    $firstChar = 65;
    $tempChar = '';
    $tempCharNum = '';
    foreach ($fields as $key => &$field) {
        //当列超出 A-Z时，为：AA-AZ,BA-BZ，以此类推
        if ($firstChar > 90) {
            $firstChar = 65; //当超出 Z 时，重新跳到 A 开始

            if ($tempChar == '') {
                $tempCharNum = 65;//当超出 Z 时，从 A 开始时需要加上 A-Z
            } else {
                $tempCharNum += 1;
            }
            $tempChar = chr($tempCharNum);
        }
        $column = chr($firstChar);
        $firstChar++;

        $char = $tempChar . $column; //哪一列

        //处理连表的导出字段
        if (is_numeric($field)) {
            $field = [
                'field' => $key,
                'comment' => $fieldComment[$key],
                'type' => 'varchar',
                'chose' => [],
            ];
        }
        $field['char'] = $char;//记录哪一列，数据循环时可直接取用
        //设置表头
        $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $field['comment']);
        //改变长度
        $objPHPExcel->getActiveSheet()->getColumnDimension($char)->setWidth(30);
    }
//            halt($fields);

    //查询数据
    $wheres = [
        // "transport.status" => ['in', '1,2']
    ];
    if ($ids != 'all' && !empty($ids)) {
        $where = [];
        $where['workLog.work_id'] = ['in', $ids];
    }
    //var_dump($wheres);
    //var_dump($where);exit;
    $list = $this->model
        ->with(['Product','User','Channel','Admin','Factory','WorkLog'])
        //->join("work_log wl","wl.work_id = work.id","left")
        //->where($wheres)
        ->where($where)
        ->select();
   // echo $this->model->getLastSql();exit;
    //输出表格
    //1待审核2已驳回3待用户寄出4待工厂收货5工厂检测中6待确认检查结果7待上传凭证8凭证待审核9待工厂寄出10已完成
    $status_arr = ['1'=>"待审核",'2'=>"已驳回",'3'=>"待用户寄出",'4'=>"待工厂收货",'5'=>"工厂检测中",'6'=>"待确认检查结果",'7'=>"待上传凭证",'8'=>"凭证待审核",'9'=>"待工厂寄出",'10'=>"已完成",'11'=>"撤回",];
    foreach ($list as $key => &$val) {
       // $list[$key]['id'] = $val['workLog.id'];


        $list[$key]['work_log>status'] = $status_arr[$val['status']];
        //$val['work_log>damage_reason'] = $val['damage_reason']==1?'非质量问题':'质量问题';


        $val = $val->toArray();
        $i = $key + 2;//表格是从2开始的,第1行为表头
        foreach ($fields as &$field) {

            $data = $val[$field['field']] ?? '';

            //连表显示的字段
            if (strpos($field['field'], '>') !== false) {
                $fieldArr = explode('>', $field['field']);
                $data = $val[$fieldArr[0]][$fieldArr[1]];
            }
            //转换为时间格式
            if (is_numeric($data) && mb_strlen($data) == 10) {
                $data = date('Y-m-d H:i:s', $data);
            }
            //设置第行高度
            $objPHPExcel->getActiveSheet()->getRowDimension($key)->setRowHeight(65);
            //将选择项转换成对应的值
            if (!empty($field['chose'])) {
                $data = $field['chose'][$data];
            }
            if($field['field'] == 'work_log>damage_reason'){
                if($data==1){
                    $data = '非质量问题';
                }elseif($data==2){
                    $data = '质量问题';
                }

            }
            $cost_str = '';
            if($field['field'] == 'work_log>cost_content_sum'){
                $work_costlist = Db::name("work_cost")->where(['work_id'=>$ids])->select();
                foreach ($work_costlist as $kk=>$vv){
                    $cost_str .= $vv['costmode_name'].",";
                }
                $data = trim($cost_str,',');
            }
            $bl_str = '';
            if($field['field'] == 'work_log>problem'){
                $problemlist = Db::name("problem")->where('id','in',$data)->select();
                foreach ($problemlist as $kk=>$vv){
                    $bl_str .= $vv['name'].",";
                }
                $data = trim($bl_str,',');
            }


            //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
            if (strpos($field['type'], 'char') !== false) {
                $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
            } else {
                $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
            }


            $bl_str_status = '';
            if($field['field'] == 'work_log>factory_status'){
                $repairlist = Db::name("repair")->where('id','in',$data)->select();
                foreach ($repairlist as $kk=>$vv){
                    $bl_str_status .= $vv['name'].",";
                }
                $data = trim($bl_str_status,',');
            }


            //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
            if (strpos($field['type'], 'char') !== false) {
                $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
            } else {
                $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
            }
        }
    }

    $outputFileName = date("YmdHis") . '导出.xls';

    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Disposition:inline;filename="' . $outputFileName . '"');
    header("Content-Transfer-Encoding: binary");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: no-cache");
    $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
    $objWriter->save('php://output');
    exit;
}
//导出数据
    public function serviceexport()
    {
        set_time_limit(0);//设置时间限制
        $ids = $this->request->post('ids'); //获取数据的所有id
        $search = $this->request->post('search'); //获取数据的所有id
        $filter = $this->request->post('filter'); //获取数据的所有id
        $op = $this->request->post('op'); //获取数据的所有id
        $columns = $this->request->post('columns'); //获取数据的所有id

//var_dump($ids);
//var_dump($filter);
////var_dump($op);
        $filter_arr = json_decode($filter,true);
        $op_arr = json_decode($op,true);
        $where = [];
        foreach ($filter_arr as $k=>$v){
            if($op_arr[$k] == 'LIKE'){
                $where[$k] = [$op_arr[$k],'%'.$v.'%'];
            }else{
                $where[$k] = [$op_arr[$k],$v];
            }

        }
        //var_dump($where);
//exit;
        //导出的字段
        /*$field = [
           'res_address','channel->name',"real_pay_time","status","admin->nickname","reject","reject_time",'admin_shipper_name','admin_shipper_code','usersend_time',"auditing_time",'confirm_time','problem'.'cost','factory_status','cost_content', 'detection_time','sales_status','confirmdetection_time','voucher_time','voucher_re','voucher_aud_re_time','voucher_aud_time','user>nickname', 'user>mobile', 'confirm_time','image'
        ];*/
        $field = [
            'id','factory>title','product>name','product>code','res_receiver','res_mobile','res_address','user_shipper_name','user_shipper_code','confirm_time','problem','damage_reason','cost','factory_status','cost_content','sales_status','confirmdetection_time','admin_shipper_name', 'admin_shipper_code','factorysend_time'
        ];
        //连表数据需要显示的字段，user>mobile表示为：user表下的mobile字段
        $fieldComment = [
            'id' => 'Id',
            'factory>title' => '所属工厂',
            'product>name' => '产品名称',
            'product>code' => '产品序列号',
            'res_receiver' => '用户名',
            'res_mobile' => '用户手机号',
            'res_address' => '用户地址',
            'user_shipper_name' => '用户寄出快递公司',
            'user_shipper_code' => '用户寄出单号',
            'confirm_time' => '工厂确认收货时间',
            'problem' => '故障问题',
            'damage_reason' => '损坏原因',
            'cost' => '售后费用',
            'factory_status' => '工厂检测维修状态',
            'cost_content' => '费用说明',
            'sales_status' => '售后客服确认维修状态',
            'confirmdetection_time' => '确认检测结果时间',
            'admin_shipper_name' => '寄出快递公司',
            'admin_shipper_code' => '物流单号',
            'factorysend_time' => '寄回时间',
        ];
        $fields = $this->getField($field);

        $objPHPExcel = new Spreadsheet();
        $firstChar = 65;
        $tempChar = '';
        $tempCharNum = '';
        foreach ($fields as $key => &$field) {
            //当列超出 A-Z时，为：AA-AZ,BA-BZ，以此类推
            if ($firstChar > 90) {
                $firstChar = 65; //当超出 Z 时，重新跳到 A 开始

                if ($tempChar == '') {
                    $tempCharNum = 65;//当超出 Z 时，从 A 开始时需要加上 A-Z
                } else {
                    $tempCharNum += 1;
                }
                $tempChar = chr($tempCharNum);
            }
            $column = chr($firstChar);
            $firstChar++;

            $char = $tempChar . $column; //哪一列

            //处理连表的导出字段
            if (is_numeric($field)) {
                $field = [
                    'field' => $key,
                    'comment' => $fieldComment[$key],
                    'type' => 'varchar',
                    'chose' => [],
                ];
            }
            $field['char'] = $char;//记录哪一列，数据循环时可直接取用
            //设置表头
            $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $field['comment']);
            //改变长度
            $objPHPExcel->getActiveSheet()->getColumnDimension($char)->setWidth(30);
        }
//            halt($fields);

        //查询数据
        $wheres = [
            // "transport.status" => ['in', '1,2']
        ];
        if ($ids != 'all' && !empty($ids)) {
            $where = [];
            $where['work.id'] = ['in', $ids];
        }
        //var_dump($wheres);
        //var_dump($where);exit;
        $work_list = Db::name("work")->where(['id'=>$ids])->find();
        $list = $this->model
            ->with(['Product','User','Channel','Admin','Factory'])
            //->where($wheres)
            ->where(['work.product_id'=>$work_list['product_id']])
            ->select();
        //echo $this->model->getLastSql();exit;
        //输出表格
        //1待审核2已驳回3待用户寄出4待工厂收货5工厂检测中6待确认检查结果7待上传凭证8凭证待审核9待工厂寄出10已完成
        $status_arr = ['1'=>"待审核",'2'=>"已驳回",'3'=>"待用户寄出",'4'=>"待工厂收货",'5'=>"工厂检测中",'6'=>"待确认检查结果",'7'=>"待上传凭证",'8'=>"凭证待审核",'9'=>"待工厂寄出",'10'=>"已完成",'11'=>"撤回",];
        foreach ($list as $key => &$val) {
            $list[$key]['user_shipper_name'] = Db::name("shipper")->where(['id'=>$val['user_shipper_id']])->value("name");
            //$list[$key]['admin_shipper_name'] = Db::name("shipper")->where(['id'=>$val['admin_shipper_id']])->value("name");
            $list[$key]['damage_reason'] = $val['status']==1?'非质量问题':'质量问题';
            $list[$key]['status'] = $status_arr[$val['status']];
            $bl_str = '';
            if($val['problem']){
                $problemlist = Db::name("problem")->where('id','in',$val['problem'])->select();
                foreach ($problemlist as $kk=>$vv){
                    $bl_str .= $vv['name'].",";
                }
            }
            $list[$key]['problem'] = trim($bl_str,',');
            $val = $val->toArray();
            $i = $key + 2;//表格是从2开始的,第1行为表头
            foreach ($fields as &$field) {
                $data = $val[$field['field']] ?? '';
                //连表显示的字段
                if (strpos($field['field'], '>') !== false) {
                    $fieldArr = explode('>', $field['field']);
                    $data = $val[$fieldArr[0]][$fieldArr[1]];
                }
                //转换为时间格式
                if (is_numeric($data) && mb_strlen($data) == 10) {
                    $data = date('Y-m-d H:i:s', $data);
                }
                //设置第行高度
                $objPHPExcel->getActiveSheet()->getRowDimension($key)->setRowHeight(65);
                //将选择项转换成对应的值
                if (!empty($field['chose'])) {
                    $data = $field['chose'][$data];
                }
                if($field['field'] == 'work_log>damage_reason'){
                    if($data==1){
                        $data = '非质量问题';
                    }elseif($data==2){
                        $data = '质量问题';
                    }

                }
                $bl_str = '';
                if($field['field'] == 'work_log>problem'){
                    $problemlist = Db::name("problem")->where('id','in',$data)->select();
                    foreach ($problemlist as $kk=>$vv){
                        $bl_str .= $vv['name'].",";
                    }
                    $data = trim($bl_str,',');
                }
                //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
                if (strpos($field['type'], 'char') !== false) {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
                }

            }
        }

        $outputFileName = date("YmdHis") . '导出.xls';

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $outputFileName . '"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $objWriter->save('php://output');
        exit;
    }
    public function export_bak()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            //带出字段，必须有id
            $columns = 'image';

            $height = 20;//通用行高
            $pic_height = 40;//图片行高
            $objPHPExcel = new \PHPExcel();
            $objActSheet = $objPHPExcel->getActiveSheet();
            //设置标题
            $title = explode(',', $columns);
            $bold = count($title);
            $objPHPExcel->getActiveSheet()->getStyle('A:'. $this->abc[$bold - 1])->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//列a至列n 垂直居中
            $objPHPExcel->getActiveSheet()->getStyle('A:'. $this->abc[$bold - 1])->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//列a至列n水平居中
            $objPHPExcel->getActiveSheet()->getStyle('A1:'. $this->abc[$bold - 1] .'1')->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight($height);//头部第一行 行高
            foreach ($title as $k => $v) {
                if ($v != 'id') {//无id版本 如若改为有id版本，删除此处$k --；全局搜‘无id版本’，再修改两处。
                    //$k --;
                    $objActSheet->setCellValue($this->abc[$k] . '1', __($v));//$objActSheet->setCellValue('A1', '编号');
                    // 设置列宽度
                    $objPHPExcel->getActiveSheet()->getColumnDimension($this->abc[$k])->setWidth(17);
                }
            }

            $whereIds = $ids == 'all' ? '1=1' : ['work.id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //自定义模型（手动创建），使用fastadmin创建的模型会有很多多余字段。
            $this->model::field($columns)
                ->where($where)
                ->where($whereIds)
                ->chunk(100, function ($items) use (&$objPHPExcel, $title, &$objActSheet, &$pic, $pic_height) {
                    $data = $items = collection($items)->toArray();
                    //自定义数据格式区域
                    foreach ($data as &$val) {
                        $val['mobile'] = " " . $val['mobile'];
                        $val['status'] = $val['status'] == 'normal' ? '营业' : '歇业';
                        $val['createtime'] = datetime($val['createtime'], "Y-m-d H:i:s");
                    }
                    unset($val);
                    foreach ($data as $k => $v) {
                        $k += 2;

                        $objPHPExcel->setActiveSheetIndex(0);
                        $objPHPExcel->getActiveSheet()->setTitle('Simple');
                        // 表格高度
                        $objActSheet->getRowDimension($k)->setRowHeight(30);
                        $pics = ['id'];//记录图片字段
                        $types = ['gif', 'jpeg', 'png', 'bmp', 'peg', 'jpg']; //定义检查的图片类型
                        //记录图片列表
                        $num = -2;// 无id版本 有id设置为0
                        $pic = [];
                        foreach ($v as $pick => $picv) {
                            $num ++;
                            if (in_array(substr($picv, strrpos($picv, '.') + 1), $types)) {
                                $pic[$pick] = $this->abc[$num];//记录图片的列表
                                //记录图片字段
                                $pics[$pick] = $picv;

                                $v[$pick] = \think\Request::instance()->domain() . $v[$pick];//拼接域名
                                $data[$k][$pick] = $v[$pick];

                                // 图片生成
                                $objDrawing[$k] = new \PHPExcel_Worksheet_MemoryDrawing();
                                // 截取图片的格式，用不同的方法

                                $end[$k] = substr($data[$k][$pick], strrpos($data[$k][$pick], '.') + 1);

                                if ($end[$k] == 'jpg' || $end[$k] == 'peg') {
                                    $img[$k] = @imagecreatefromjpeg($data[$k][$pick]);
                                } else if ($end[$k] == 'png') {
                                    $img[$k] = @imagecreatefrompng($data[$k][$pick]);
                                } else if ($end[$k] == 'gif') {
                                    $img[$k] = @imagecreatefromgif($data[$k][$pick]);
                                }
                                $objDrawing[$k]->setImageResource($img[$k]);
                                $objDrawing[$k]->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT);//渲染方法

                                $objDrawing[$k]->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                                // // 设置宽度高度
                                $objDrawing[$k]->setHeight(40);//照片高度
                                $objDrawing[$k]->setWidth(40); //照片宽度
                                // /*设置图片要插入的单元格*/
                                //$objDrawing[$k]->setCoordinates('G' . $k);
                                $objDrawing[$k]->setCoordinates($pic[$pick] . $k);
                                // // 图片偏移距离
                                $objDrawing[$k]->setOffsetX(8);
                                $objDrawing[$k]->setOffsetY(8);
                                $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());
                                // 表格高度
                                $objActSheet->getRowDimension($k)->setRowHeight($pic_height);
                            }
                        }
                        //渲染数据
                        foreach ($title as $i => $j) {
                            if (!isset($pics[$j])) {
                                //无id版本
                                if ($this->abc[$i] != 'A') {
                                    $objActSheet->setCellValue($this->abc[--$i] . $k, $v[$j]);//$objActSheet->setCellValue('A' . $k, $v['id']);
                                }
                            }
                        }
                    }
                });

            $fileName = '质保公司管理';
            $date = date("Y-m-d", time());
            $fileName .= "_{$date}.xls";
            $fileName = iconv("utf-8", "gb2312", $fileName);
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output'); //文件通过浏览器下载

            return;
        }
    }
    protected $abc = [

        0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G', 7 => 'H', 8 => 'I', 9 => 'J',
        10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N', 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T',
        20 => 'U', 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'Y', 25 => 'Z', 26 => 'AA', 27 => 'AB', 28 => 'AC', 29 => 'AD',
        30 => 'AE', 31 => 'AF', 32 => 'AG', 33 => 'AH', 34 => 'AI', 35 => 'AJ', 36 => 'AK', 37 => 'AL', 38 => 'AM', 39 => 'AN',
        40 => 'AO', 41 => 'AP', 42 => 'AQ', 43 => 'AR', 44 => 'AS', 45 => 'AT', 46 => 'AU', 47 => 'AV', 48 => 'AW', 49 => 'AX',
        50 => 'AY', 51 => 'AZ', 52 => 'BA', 53 => 'BB', 54 => 'BC', 55 => 'BD', 56 => 'BE', 57 => 'BF', 58 => 'BG', 59 => 'BH',
        60 => 'BI', 61 => 'BJ', 62 => 'BK', 63 => 'BL', 64 => 'BM', 65 => 'BN', 66 => 'BO', 67 => 'BP', 68 => 'BQ', 69 => 'BR',
        70 => 'BS', 71 => 'BT', 72 => 'BU', 73 => 'BV', 74 => 'BW', 75 => 'BX', 76 => 'BY', 77 => 'BZ', 78 => 'CA', 79 => 'CB',
        80 => 'CC', 81 => 'CD', 82 => 'CE', 83 => 'CF', 84 => 'CG', 85 => 'CH', 86 => 'CI', 87 => 'CJ', 88 => 'CK', 89 => 'CL',
        90 => 'CM', 91 => 'CN', 92 => 'CO', 93 => 'CP', 94 => 'CQ', 95 => 'CR', 96 => 'CS', 97 => 'CT', 98 => 'CU', 99 => 'CV'
    ];
    /**
     * 获取导出表信息
     * @param $field array 需要显示的字段
     * @return int[]|string[]
     */
    public function getField($field = [])
    {
        $prefix = config('database')['prefix'];
        $table = "fa_work";//查询的表名（带前缀）
        $data = Db::query('SHOW FULL COLUMNS FROM ' . $table);

        $returnField = array_flip($field);  //键值对换
        //判断跳过注释为空的和需要忽略的字段
        foreach ($data as $val) {
            $add = [];
            //只获取导出的字段
            if (!in_array($val['Field'], $field)) continue;

            if ($val['Comment'] != '') {
                $add['field'] = $val['Field'];  //字段
                $add['comment'] = $val['Comment']; //注释
                $add['type'] = $val['Type']; //数据类型
                $add['chose'] = []; //选择项，当注释包含格式：类型:1=大,2=小，才有选择项
                //处理选择项
                if (strpos($val['Comment'], ':') !== false) {
                    $commentArr = explode(':', $val['Comment']);
                    $add['comment'] = $commentArr[0];
                    $commentArr = explode(',', $commentArr[1]);
                    foreach ($commentArr as $k => $v) {
                        $commentArr = explode('=', $v);
                        $add['chose'][$commentArr[0]] = $commentArr[1];
                    }
                }
                $returnField[$val['Field']] = $add;
            }
        }
        return $returnField;
    }
    public function xiugai($ids=null){
        $row = $this->model->get($ids);
        $chehui = $this->request->post('chehui');
        $id = $this->request->post('id');
        $params = $this->request->post('row/a');
        $params['ago_admin_id'] = $this->auth->id;
        if ( $this->request->isPost()) {
            if($this->auth->id){
                $product_data = Db::name("product")->where(['id'=>$params['product_id']])->find();
                if(!$product_data){
                    $this->error("数据有误");
                }
                $uin_add['product_id'] = $params['product_id'];
                $uin_add['factory_id'] = $product_data['factory_id'];
                //$uin_add['image'] = $params['image'];
                $uin_add['user_content'] = $params['user_content'];
                //$uin_add['admin_id'] = $params['admin_id'];
                //$uin_add['channel_id'] = $params['channel_id'];
                //$uin_add['order_image'] = $params['order_image'];
                $uin_add['res_receiver'] = $params['res_receiver'];
                $uin_add['res_mobile'] = $params['res_mobile'];
                $uin_add['res_address'] = $params['res_address'];
                $uin_add['user_shipper_code'] = isset($params['user_shipper_code'])?$params['user_shipper_code']:"";
                $uin_add['shop_name'] = $params['shop_name'];
                $uin_add['order_code'] = $params['order_code'];
                $uin_add['confirm_time'] = isset($params['confirm_time'])?strtotime($params['confirm_time']):"";
                $uin_add['ago_admin_id'] = $this->auth->id;
                $uin_add['createtime'] = time();
                if($params['isstatus'] == 2){//自动审核通过
                    $uin_add['status'] = 3;
                }
                if(isset($params['user_shipper_code'])){
                    $uin_add['status'] = 5;
                }
                //echo $params['id']."__".$params['product_name'];exit();
                $id = Db::name("work")->where(['id'=>$params['id']])->update($uin_add);
                if(isset($params['admin_id'])){
                    \app\admin\model\User::adminnews($params['admin_id'],"工单待审核通知","您有工单需要审核请尽快审核",$id);
                }
                $this->success("添加成功");
            }else{
                $this->token();
            }

        }else{
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_title'] = $factory['title'];
            $list['factory_phone'] = $factory['phone'];
            $list['factory_name'] = $factory['name'];
            $list['factory_address'] = $factory['address'];

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $this->view->assign( 'row', $list);
            $this->view->assign("ids", $ids);
            $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
            $this->view->assign("admin_type", $admin_type);
            return $this->view->fetch();
        }


        $updata['status'] = $chehui;
        Db::name("work")->where(['id'=>$id])->update($updata);
        $this->success("操作成功");
    }
    public function xiugaiputong($ids=null){
        $row = $this->model->get($ids);
        $chehui = $this->request->post('chehui');
        $id = $this->request->post('id');
        $params = $this->request->post('row/a');
        $params['ago_admin_id'] = $this->auth->id;
        if ( $this->request->isPost()) {
            if($this->auth->id){
                $product_data = Db::name("product")->where(['id'=>$params['product_id']])->find();
                if(!$product_data){
                    $this->error("数据有误");
                }
                $uin_add['product_id'] = $params['product_id'];
                $uin_add['factory_id'] = $product_data['factory_id'];
                //$uin_add['image'] = $params['image'];
                $uin_add['user_content'] = $params['user_content'];
                //$uin_add['admin_id'] = $params['admin_id'];
                //$uin_add['channel_id'] = $params['channel_id'];
                //$uin_add['order_image'] = $params['order_image'];
                $uin_add['res_receiver'] = $params['res_receiver'];
                $uin_add['res_mobile'] = $params['res_mobile'];
                $uin_add['res_address'] = $params['res_address'];
                if(isset($params['detection_content'])){
                    $uin_add['detection_content'] = $params['detection_content'];
                }
                if(isset($params['cost_content'])){
                    $uin_add['cost_content'] = $params['cost_content'];
                }
                if(isset($params['user_shipper_code'])){
                    $uin_add['user_shipper_code'] = $params['user_shipper_code'];
                }
                if(isset($params['confirm_time'])){
                    $uin_add['confirm_time'] = $params['confirm_time'];
                }
                if(isset($params['shop_name'])){
                    $uin_add['shop_name'] = $params['shop_name'];
                }
                if(isset($params['order_code'])){
                    $uin_add['order_code'] = $params['order_code'];
                }
                $uin_add['ago_admin_id'] = $this->auth->id;
               // $uin_add['detection_content'] = time();
                //echo $params['id']."__".$params['product_name'];exit();
                $id = Db::name("work")->where(['id'=>$params['id']])->update($uin_add);
                if(isset($params['admin_id'])){
                    \app\admin\model\User::adminnews($params['admin_id'],"工单待审核通知","您有工单需要审核请尽快审核",$id);
                }
                $this->success("添加成功");
            }else{
                $this->token();
            }

        }else{
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_title'] = $factory['title'];
            $list['factory_phone'] = $factory['phone'];
            $list['factory_name'] = $factory['name'];
            $list['factory_address'] = $factory['address'];

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            $list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            $this->view->assign( 'row', $list);
            $this->view->assign("ids", $ids);
            $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
            $this->view->assign("admin_type", $admin_type);
            $this->view->assign("status", $list['status']);
            return $this->view->fetch();
        }


        $updata['status'] = $chehui;
        Db::name("work")->where(['id'=>$id])->update($updata);
        $this->success("操作成功");
    }

    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 工作流
     */
    public function worklog($ids=null){
        $list = Db::name("work")->alias('w')
            ->field("w.*,p.code as product_code,p.name as product_name")
            ->join("product p",'w.product_id = p.id', 'LEFT')
            ->where(['w.id'=>$ids])
            ->find();
        //$result = array("row" => $list);
        $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
        $where_r['id'] = $product['factory_id'];
        $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
        //echo Db::name("factory")->getLastSql();
        $list['factory_tile'] = $factory['title'];

        $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
        $list['admin_username'] = $admin['username'];
        $work_log = Db::name("work_log")->where(['work_id'=>$ids])->select();
        $str = "";
        foreach ($work_log as $k=>$v){
            $str .= date('Y-m-d H:i:s',$v['createtime'])." ".$v['content']."<br>";
        }
        $list['log'] = $str;
            $this->view->assign( 'row', $list);
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }
    public function workCost($id){
        $goods_list = Db::name("work_cost")->where(['work_id'=>$id])->select();
        return json($goods_list);
    }
    public function service($ids){
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }
    public function serviceList($id){
        $work_list = Db::name("work")->where(['id'=>$id])->find();
        $service_list = Db::name("work")->alias("w")
            ->field("w.*,p.name product_name,p.code product_code,p.factory_id,u.nickname,c.name channel_name")
            ->join("product p",'w.product_id = p.id', 'LEFT')
            ->join("user u","u.id = w.user_id", 'LEFT')
            ->join("channel c","c.id = w.channel_id", 'LEFT')
            ->where(['w.product_id'=>$work_list['product_id'],'res_mobile'=>$work_list['res_mobile']])
            ->select();
        $status_arr = ['1'=>"待审核",'2'=>"已驳回",'3'=>"待用户寄出",'4'=>"待工厂收货",'5'=>"工厂检测中",'6'=>"待确认检查结果",'7'=>"待上传凭证",'8'=>"凭证待审核",'9'=>"待工厂寄出",'10'=>"已完成",'11'=>"撤回",];
        foreach ($service_list as $k=>$v){
            $service_list[$k]["factory_title"] = Db::name("factory")->where(['id'=>$v['factory_id']])->value("title");
            $service_list[$k]["status_name"] = $status_arr[$v['status']];
            $service_list[$k]["res_receiver"] = $v['res_receiver']?$v['res_receiver']:'';
            $service_list[$k]["createtime"] = date("Y-m-d H:i:s",$v['createtime']);
        }
        return json($service_list);
    }
    public function tongxiugai($ids=null){
        $row = $this->model->get($ids);
        $chehui = $this->request->post('chehui');
        $id = $this->request->post('id');
        $params = $this->request->post('row/a');
        $params['ago_admin_id'] = $this->auth->id;
        if ( $this->request->isPost()) {
            if($this->auth->id){

                foreach ($params['problem'] as $k=>$v){
                    if($v == 0){
                        unset($params['problem'][$k]);
                    }
                }

                $is_liugc = isset($params['is_liugc'])?$params['is_liugc']:0;
                //$uin_add['image'] = $params['image'];
                $uin_add['user_content'] = $params['user_content'];
                if(isset($params['image'])){
                    $uin_add['image'] = $params['image'];
                }
                if(isset($params['order_image'])){
                    $uin_add['order_image'] = $params['order_image'];
                }

                $uin_add['cost'] = $params['cost'];
                $uin_add['real_cost'] = $params['real_cost'];
                $uin_add['cost_content'] = $params['cost_content'];
                //$uin_add['admin_id'] = $params['admin_id'];
                //$uin_add['channel_id'] = $params['channel_id'];
                //$uin_add['order_image'] = $params['order_image'];
                $uin_add['res_receiver'] = $params['res_receiver'];
                $uin_add['res_mobile'] = $params['res_mobile'];
                $uin_add['res_address'] = $params['res_address'];
                $uin_add['user_shipper_code'] = isset($params['user_shipper_code'])?$params['user_shipper_code']:"";
                $uin_add['is_liugc'] = $is_liugc;
                $uin_add['shop_name'] = $params['shop_name'];
                $uin_add['order_code'] = $params['order_code'];
                $uin_add['sales_status'] = $params['sales_status'];
                $uin_add['cost'] = $params['cost'];
                $uin_add['remarks'] = $params['remarks'];
                $uin_add['user_shipper_id'] = $params['user_shipper_id'];
                $uin_add['voucher'] = $params['voucher'];
                $uin_add['problem_content'] = $params['problem_content'];
                $uin_add['detection_content'] = $params['detection_content'];
                $uin_add['real_pay_time'] = $params['real_pay_time'];

                $uin_add['confirm_time'] = isset($params['confirm_time'])?strtotime($params['confirm_time']):"";
                $uin_add['confirmdetection_time'] = isset($params['confirmdetection_time'])?strtotime($params['confirmdetection_time']):"";
                $uin_add['ago_admin_id'] = $this->auth->id;
                $uin_add['createtime'] = time();
                $uin_add['problem'] = implode(',', $params['problem']);
                $uin_add['factory_status'] = implode(',', $params['factory_status']);
                if(isset($params['linedetail'])){
                    Db::name("work_cost")->where(['work_id'=>$ids])->delete();
                    foreach ($params['linedetail'] as $k=>$v){
                        $w_arr['factory_title'] = $v['factory_title'];
                        $w_arr['product_name'] = $v['product_name'];
                        $w_arr['costmode_name'] = $v['costmode_name'];
                        $w_arr['cost_money'] = $v['cost_money'];
                        $w_arr['real_money'] = $v['real_money'];
                        $w_arr['work_id'] = $ids;
                        //echo $params['checkbox'.$k];
                        $checkbox = $this->request->post('checkbox'.$k);
                        if(isset($checkbox) && $checkbox == 'on'){
                            $w_arr['type'] = 1;
                        }else{
                            $w_arr['type'] = 0;
                        }
                        $work_cost_arr[] = $w_arr;
                    }
                    Db::name("work_cost")->insertAll($work_cost_arr);
                }
                //echo $params['id']."__".$params['product_name'];exit();
                if($is_liugc == 1){
                    $uin_add['status'] = 10;
                }
                $id = Db::name("work")->where(['id'=>$params['id']])->update($uin_add);
                if(isset($params['admin_id'])){
                    \app\admin\model\User::adminnews($params['admin_id'],"工单待审核通知","您有工单需要审核请尽快审核",$id);
                }
                $this->success("添加成功");
            }else{
                $this->token();
            }

        }else{
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name")
                ->join("product p",'w.product_id = p.id', 'LEFT')
                ->where(['w.id'=>$ids])
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_title'] = $factory['title'];
            $list['factory_phone'] = $factory['phone'];
            $list['factory_name'] = $factory['name'];
            $list['factory_address'] = $factory['address'];

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $list['channel_name'] = $channel['name'];
            if(!$list['confirm_time']){
                $list['confirm_time'] = 0;
            }
            $this->view->assign("confirm_time", $list['confirm_time']);
            $list['confirm_time'] = date('Y-m-d H:i:s',$list['confirm_time']);
            $list['confirmdetection_time'] = date('Y-m-d H:i:s',$list['confirmdetection_time']);
            //$list['res_address'] = $list['res_receiver']."-".$list['res_mobile']."-".$list['res_address'];
            //var_dump($list);
            $this->view->assign( 'factory_id', $product['factory_id']);
            $this->view->assign( 'product_id', $list['product_id']);
            $this->view->assign( 'row', $list);
            $this->view->assign("ids", $ids);
            $this->view->assign("damage_reason", $list['damage_reason']);

            $admin_type = Db::name("admin")->where(['id'=>$this->auth->id])->value("type");
            $this->view->assign("admin_type", $admin_type);
            return $this->view->fetch();
        }


        $updata['status'] = $chehui;
        Db::name("work")->where(['id'=>$id])->update($updata);
        $this->success("操作成功");
    }
    public function chagewc($id = null){

        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $updata['status'] = 10;
        Db::name("work")->where(['id'=>$id])->update($updata);
        $this->success("成功");
    }
}
